代码第四行里新建一个script标签页,在第8行的回调函数onreadystatechange里,根据属性readyState判断当前标签页的状态,如果为loaded或者complete,说明脚本加载成功,此时触发脚本加载人员指定的回调函数。
该加载器的完整代码实现如下:
<html>
<script>
function loadScript(url, callback){
var script = document.createElement ("script") ;
script.type = "text/javascript";
if (script.readyState){ //IE
script.onreadystatechange = function(){
if (script.readyState == "loaded" || script.readyState == "complete"){
script.onreadystatechange = null;
callback();
} // end of readyState
}; // end of onreadystatechange
} // end of IE
else {
script.onload = function(){
callback();
};
}
script.src = url;
document.getElementsByTagName("head")[0].appendChild(script);
}
loadScript("026_test.js", function(){
console.log("File is loaded!");
hello();
});
</script>
</html>
新建一个测试脚本文件,命名为test.js:
function hello() {
console.log("hello world");
}
使用下列代码加载该脚本,加载成功后,回调函数打印出File is loaded的消息,同时被加载脚本test.js里的函数hello被调用,打印出hello world:
要获取更多Jerry的原创文章,请关注公众号"汪子熙":