JS 异步加载的方法

(1) defer,只支持IE :

<script type="text/javascript" defer="defer"> </script>

(2) async:属性

<script type="text/javascript" src="demo_async.js" async="async"></script> 

 

(3) 创建script,插入到DOM中,加载完毕后callBack,见代码:

function loadScript(url, callback){ 
var script = document.createElement_x("script") 
script.type = "text/javascript"; 
if (script.readyState){ //IE 
script.onreadystatechange = function(){ 
if (script.readyState == "loaded" || 
script.readyState == "complete"){ 
script.onreadystatechange = null; 
callback(); 
} 
}; 
} else { //Others: Firefox, Safari, Chrome, and Opera 
script.onload = function(){ 
callback(); 
}; 
} 
script.src = url; 
document.body.appendChild(script); 
} 

  

posted @ 2016-09-26 11:25  Terre  阅读(262)  评论(0编辑  收藏  举报

风光无限好