Skip to content Skip to sidebar Skip to footer

Require_once Like For Javascript ?

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 #ifndef(.c/.c++).

Solution 1:

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.


Solution 2:

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.


Post a Comment for "Require_once Like For Javascript ?"