要实现非阻塞js(non-blocking javascript)有两个方法:1. html5 2. 动态加载js 首先一种办法是HTML5的defer和async关键字:
defer: <script type="text/javascript" defer src="foo.js"></script> async: <script type="text/javascript" async src="foo.js"></script>
然后第二种方法是动态加载js:
setTimeout(function(){ var script = document.createElement("script"); script.type = "text/javascript"; script.src = "foo.js"; var head = true; //加在头还是尾 if(head) document.getElementsByTagName("head")[0].appendChild(script); else document.body.appendChild(script); }, 0); //另外一个独立的动态加载js的函数function loadJs(jsurl, head, callback){ var script=document.createElement('script'); script.setAttribute("type","text/javascript"); if(callback){ if (script.readyState){ //IE script.onreadystatechange = function(){ if (script.readyState == "loaded" || script.readyState == "complete"){ script.onreadystatechange = null; callback(); } }; } else { //Others script.onload = function(){ callback(); }; } } script.setAttribute("src", jsurl); if(head) document.getElementsByTagName('head')[0].appendChild(script); else document.body.appendChild(script); }
动态加载js
最新推荐文章于 2024-07-02 19:46:13 发布