我为javascript制作了一个命名空间框架。我正在加载一些动态添加到 HTML 中的插件(.js 文件)。
我将尝试简化代码。
此函数用于动态加载 JS。加载 .js 文件后调用回调函数。考虑以下代码已经运行。
MYNAMESPACE.plugins = ["plugin1", "plugin2"];
MYNAMESPACE.getJS = {
get: function (url, callback) {
var script = document.createElement("script");
var head = document.getElementsByTagName('head')[0];
script.type = "text/javascript";
script.src = url;
head.insertBefore(script, head.firstChild)
script.onload = callback;
script.onreadystate = callback;
return script;
}
};
我有一个 init 函数,它加载 MYNAMESPACE.plugins 中包含的插件,如下所示:
MYNAMESPACE.init = function (callback) {
for (index in MYNAMESPACE.plugins) {
plugin = MYNAMESPACE.plugins[index];
MYNAMESPACE.getJS.get(plugin + '.js', function ()
{
// This callback is executed when the js file is loaded
});
}
// Here I want to execute callback function, but after all the callbacks in the for loop have been executed. Something like: if (alljsloaded) callback();
}
在我的 HTML 中,我有以下脚本标签:
<html>
<head>
<script type="text/javascript">
$(document).ready(function () {
MYNAMESPACE.init();
// The following line is not executed correctlybecause init finished before the scripts are loaded and the functionOnPlugin1 is undefined.
MYNAMESPACE.functionOnPlugin1();
});
</script>
</head>
<body>
</body>
</html>
我想把它改成这样:
<html>
<head>
<script type="text/javascript">
$(document).ready(function () {
MYNAMESPACE.init(function() { MYNAMESPACE.functionOnPlugin1(); });
});
</script>
</head>
<body>
</body>
</html>
但我不知道如何修改函数 MYNAMESPACE.init() 以便在加载所有插件脚本后执行回调。
有任何想法吗?也许使用闭包。