1 function loadScript(url, callback) { 2 var script = document.createElement("script"); 3 script.type = "text/javascript"; 4 5 if (script.readyState) { //IE 6 script.onreadystatechange = function() { 7 if (script.readyState == "loaded" || script.readyState == "complete") { 8 script.onreadystatechange = null; 9 callback(); 10 } 11 }; 12 } else { 13 script.onload = function() { //其他浏览器 14 callback(); 15 }; 16 } 17 script.src = url; 18 document.getElementsByTagName("head")[0].appendChild(script); 19 }
用法如下:
1 loadScript("file1.js", function() { 2 console.log("File is loaded!"); 3 }); 4 loadScript("file1.js", function() { 5 loadScript("file2.js", function() { 6 loadScript("file3.js", function() { 7 console.log("All files are loaded!"); 8 }); 9 }); 10 });