JS 异步加载的方法
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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); }
以上是关于JS 异步加载的方法的主要内容,如果未能解决你的问题,请参考以下文章
如何延迟或异步此 WordPress javascript 片段以最后加载以加快页面加载时间?