开发者

require_once like for javascript ?

开发者 https://www.devze.com 2023-02-14 06:56 出处:网络
I\'m currently searching a solution to n开发者_如何学Cot include two times the same .js So my question is relatively simple, i\'m searching something like requice_once (.php) or #ifndef(.c/.c++).

I'm currently searching a solution to n开发者_如何学Cot include two times the same .js

So my question is relatively simple, i'm searching something like requice_once (.php) or #ifndef(.c/.c++).

Are they solution for this ?


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.


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.


You can include this file at the top of your HTML page.

include.js:

/* require.js */
if (typeof includedScripts === 'undefined')
{
    includedScripts = [];

    function isIncluded(name)
    {
        return includedScripts.includes(name);
    }

    function includeThis(name)
    {
        includedScripts.push(name);
    }
}

Then at the top of each subsequent included file, you can test and set, using this (e.g. for scripts/ajax.js here):

if (isIncluded("scripts/ajax")) exit;
includeThis("scripts/ajax");

This uses a global array, includedScripts, to track which scripts are included. This is a similar pattern to the very old C header file include test:

#ifndef __myFile
#define __myFile

/* content of your file here */

#endif

0

精彩评论

暂无评论...
验证码 换一张
取 消