有以下几种方法可以使用非阻塞方式下载 JavaScript,提快页面加载

it2022-05-05  112

为<script>标签添加defer属性(只适用于Internet Explorer 和Firefox 3.5 以上版本) <script type="text/javascript" src="file1.js"  defer></script>

动态创建<script>元素,用它下载并执行代码 1 function loadScript (url, callback){ 2 var script = document.createElement ("script") 3 script.type = "text/javascript"; 4 if (script.readyState){ //IE 5 script.onreadystatechange = function(){ 6 if (script.readyState == "loaded" || script.readyState == "complete"){ 7 script.onreadystatechange = null; 8 callback(); 9 } 10 }; 11 } else { //Others 12 script.onload = function(){ 13 callback(); 14 }; 15 } 16 script.src = url; 17 document.getElementsByTagName_ r("head")[0].appendChild(script); 18 } 1 loadScript("file1.js", function(){ 2 alert("File is loaded!"); 3 }); 用XHR对象下载代码,并注入到页面中 1 var xhr = new XMLHttpRequest(); 2 xhr.open("get", "file1.js", true); 3 xhr.onreadystatechange = function(){ 4 if (xhr.readyState == 4){ 5 if (xhr.status >= 200 && xhr.status < 300 || xhr.status == 304){ 6 var script = docume nt.createElement ("script"); 7 script.type = "text/javascript"; 8 script.text = xhr.responseText; 9 document.body.appendChild(script); 10 } 11 } 12 }; 13 xhr.send(null);

 

一些动态加载javascript文件的类库LazyLoad是一个更强大的 loadScript() 函数 1 <script type="text/javascript" src="lazyload-min.js"></script> 2 <script type="text/javascript"> 3 LazyLoad.js(["first-file.js" , "the-rest.js"], function(){ 4 Application.init(); 5 }); 6 </script>

LABjs library

1 <script type="text/javascript" src="lab.js"></script> 2 <script type="text/javascript"> 3 $LAB.script("first-file.js") 4 .script("the-rest.js") 5 .wait(function(){ 6 Application.init(); 7 }); 8 </script>

 

转载于:https://www.cnblogs.com/sencha/p/3142748.html

相关资源:让浏览器非阻塞加载javascript的几种方法小结

最新回复(0)