require_once like for javascript ?

后端 未结 2 880
夕颜
夕颜 2021-02-13 21:14

I\'m currently searching a solution to not include two times the same .js

So my question is relatively simple, i\'m searching something like requice_once (.php) or #ifnd

相关标签:
2条回答
  • 2021-02-13 21:18

    I would suggest that you use either require.js or head.js for this kind of thing. They are fully-featured and provide performance benefits as well.

    0 讨论(0)
  • 2021-02-13 21:36

    You can write your own ifndef-code, just write your files like this (assuming it's for a browser):

    if (!window.NAME_UNIQUE_FOR_THIS_FILE) {
      window.NAME_UNIQUE_FOR_THIS_FILE = true;
    
      .. your code here ...
    
    }
    

    The if-statement checks if the uniquely named variable exists already. If not, create it (so the next time this code is seen, it will be ignored). Then run whatever you want this file to do.

    Be sure to use a very unique name though, since it's a global variable.

    0 讨论(0)
提交回复
热议问题