生活随笔
收集整理的這篇文章主要介紹了
实现页面异步加载
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
應(yīng)用場(chǎng)景
平時(shí)我們用的最多的網(wǎng)頁加載方式就是同步加載模式,也稱阻塞模式,這種模式雖然安全,但是對(duì)于設(shè)計(jì)比較繁瑣的網(wǎng)頁采用同步加載會(huì)使網(wǎng)頁的加載時(shí)間大大加長(zhǎng),所以也就出現(xiàn)了下面用到的異步加載模式。
使用
異步加載可以使用 XHR Injection、 XHR Eval、 Script In Iframe、 Script defer屬性、 document.write(script tag)等,我當(dāng)前采用的的是Script DOM Element方法,也就是動(dòng)態(tài)向頁面創(chuàng)建script標(biāo)簽異步加載JS腳本。
代碼
var init = {menu: $(".menu li"),content: $(".content li"),js0: true,initSwitch: function() {var _self = this;this.menu.on('click', function() {var _index = $(this).index();if(!_self['js' + _index]) {console.log('script is loading...')_self.asyncScript("js/module" + (_index + 1) + ".js", function() {console.log('script is loaded.')_self['js' + _index] = true});}console.log('switch:'+_index)_self.menu.removeClass('mu-act').eq(_index).addClass('mu-act');_self.content.removeClass('cont-act').eq(_index).addClass('cont-act');})},asyncScript: function(urls, callback) {var script = document.createElement("script");script.type = "text/javascript";script.async = true;script.src = urls;if(script.readyState) { //IEscript.onreadystatechange = function() {if(script.readyState == "loaded" || script.readyState == "complete") {script.onreadystatechange = null;if(callback) callback()}};} else { //Othersscript.onload = function() {if(callback) callback()}}document.getElementsByTagName("body")[0].appendChild(script);}
}
init.initSwitch()
原理實(shí)現(xiàn)
主要原理就是首次加載只加載所需腳本文件,首次切換其他頁面時(shí),動(dòng)態(tài)加載所需腳本,并標(biāo)識(shí)已加載防止重復(fù)加載,異步回調(diào)方法可以在腳本加載完成時(shí)執(zhí)行相關(guān)操作。
注意
如果調(diào)用的JS內(nèi)容存在下面兩種情況都會(huì)報(bào)錯(cuò):
在chrom上面就提示”Failed to execute 'write' on 'Document': It isn't possible to write into a document from an asynchronously-loaded external script unless it is explicitly opened. “ js調(diào)用 了document.write 或者通過js 自動(dòng)創(chuàng)建script標(biāo)簽加載內(nèi)容 GitHub 源文件
https://github.com/lizhixuan1/JavaScript/tree/Async-Load
需要的朋友可以參考,如有不足,歡迎交流評(píng)論
轉(zhuǎn)載于:https://www.cnblogs.com/lizhixuan/p/9503391.html
總結(jié)
以上是生活随笔 為你收集整理的实现页面异步加载 的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔 網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔 推薦給好友。