当我们为 javascript 进行动态插入时,有时顺序很重要。我们有时通过使用 onload 属性来解决这个问题;但是,如果有很多外部javascript,并且这些脚本必须按顺序加载,那我们该怎么办?
我通过递归定义的 onload 函数解决了这个问题;但是对效率不太确定......因为这是一个脚本,我认为它确实懒惰评估......有什么帮助吗?
//recursively create external javascript loading chain
//cautiously add url list according to the loading order
//this function takes a list of urls of external javascript
function loadScript(url) {
if( url.length == 0) {
//final function to execute
return FUNCTION;
}
var f = function(){
var script = document.createElement("script");
script.type = "text/javascript";
script.src = url.pop();
//recursion
script.onload = loadScript(url) ;
document.getElementsByTagName("head")[0].appendChild(script);
}
return f;
}
function loadScripts(urls) {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = urls.pop();
script.onload = loadScript(urls) ;
document.getElementsByTagName("head")[0];.appendChild(script);
}
loadScripts(["aaa.js","bbb.js","ccc.js"]);
谢谢!
- 很抱歉让您感到困惑.. 我添加了一个实际调用 loadScript() 的函数。(我检查了这个作品..)