延迟加载JavaScript

上代码:

这段代码放到HTML文档的</body>标签之前(靠近HTML文档底部)。外部脚本的名称为defer.js

<script type="text/javascript">

function downloadJSAtOnload() {
    var element = document.createElement("script");
    element.src = "defer.js";
    document.body.appendChild( element );
}

if ( window.addEventListener ) {
    window.addEventListener( "load", downloadJSAtOnload, false );
} else if ( window.attachEvent ) {
    window.attachEvent( "onload", downloadJSAtOnload );
} else { 
    window.onload = downloadJSAtOnload;
}
</script>

参考:

http://www.cnblogs.com/yangyoucun/p/6337360.html#undefined

posted @ 2017-01-22 18:49  最爱小虾  阅读(200)  评论(0编辑  收藏  举报