javascript延迟加载的解决方案:
1.使用defer标签
-
<span style="font-size: small;"><script type="text/javascript" src="load.js" defer></script></span>
2.使用XMLHttpRequest对象加载
<span style="font-size: small;">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);</span>
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>
<script type="text/javascript" src="load.js" async="true"></script>
本文作者:记者 来源:CIOZJ
CIO之家 www.ciozj.com 微信公众号:imciow