我目前正在寻找一个解决方案,以避免重复包含同一个 .js 文件。
所以我的问题比较简单,我正在寻找类似于 require_once (.php) 或 #ifndef(.c/.c++) 的东西。
它们可以解决这个问题吗?
所以我的问题比较简单,我正在寻找类似于 require_once (.php) 或 #ifndef(.c/.c++) 的东西。
它们可以解决这个问题吗?
您可以编写自己的#ifndef代码,只需按照以下方式编写文件(假设是为浏览器编写的):
if (!window.NAME_UNIQUE_FOR_THIS_FILE) {
window.NAME_UNIQUE_FOR_THIS_FILE = true;
.. your code here ...
}
您可以在 HTML 页面的顶部包含此文件。
include.js:
/* require.js */
if (typeof includedScripts === 'undefined')
{
includedScripts = [];
function isIncluded(name)
{
return includedScripts.includes(name);
}
function includeThis(name)
{
includedScripts.push(name);
}
}
然后在每个后续包含的文件顶部,您可以使用以下内容进行测试和设置(例如,在此处使用scripts/ajax.js):
if (isIncluded("scripts/ajax")) exit;
includeThis("scripts/ajax");
此处使用全局数组includedScripts来跟踪包含的脚本。这是类似于非常古老的C头文件包含测试的模式:
#ifndef __myFile
#define __myFile
/* content of your file here */
#endif