當我們爲javascript做動態插入時,有時順序很重要。我們有時通過使用onload屬性來解決這個問題;但是,如果有很多外部JavaScript,並且這些腳本必須按順序加載,那麼我們應該怎麼做?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"]);
謝謝!
-sorry for confusing you ..我添加了一個實際調用loadScript()的函數。 (我檢查了這個作品..)
你有沒有考慮過使用諸如requireJS或像Dojo這樣的支持模塊的JS框架的現成加載器? – hugomg