如何確保頁面中的js加載完全后再執(zhí)行其他代碼
如何確定一個(gè)js是否加載完全或者頁面中的所有js加載完全,具體辦法如下:
function loadScript(url , callback){
var script = document.createElement("script");
script.type="text/javascript";
if(script.readyState){
script.onreadystatechange = function(){
if(script.readyState=="loaded"||script.readyState=="complete"){
script.onreadystatechange=null;
callback();
}
}
}else{
script.onload = function(){
callback();
}
}
script.src = url;
document.getElementsByName("head")[0].appendChild(script);
}
如何讓腳本的執(zhí)行順序按照你設(shè)定的順序執(zhí)行,使用嵌套的方式:
loadScript("file1.js",function(){
loadScript("file2.js",function(){
loadScript("file3.js",function(){
alert("All files are loaded");
});
});
});
當(dāng)然如果你熟悉jquery的話,代碼更簡單:
$.getScript("file1.js", function(){
alert("Script loaded and executed.");
});

浙公網(wǎng)安備 33010602011771號