require_once like for javascript ?

后端 未结 2 884
夕颜
夕颜 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: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.

提交回复
热议问题