日期:2014-05-16 浏览次数:20406 次
javascript延迟加载的解决方案:
1.使用defer标签
<script type="text/javascript" src="load.js" defer></script>
?2.使用XMLHttpRequest对象加载
var xhr = new XMLHttpRequest();
xhr.open("get","load.js",true);
xhr.onreadystatechange=function(){
if(readyState==4){
if(status>=200&&status<300||status==304){
var script = document.createElement("script");
script.type = "text/javascript";
script.src = xhr.responseText;
document.body.appendChild(script);
}
}
}
xhr.send(null);
?
3.使用推荐的无阻塞模式:
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); }
?4.HTML5中可以使用async方式设置异步加载js
?
?
<script type="text/javascript" src="load.js" async="true"></script>
?
?
?
?