日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

实现页面异步加载

發(fā)布時(shí)間:2024/3/13 编程问答 38 豆豆
生活随笔 收集整理的這篇文章主要介紹了 实现页面异步加载 小編覺得挺不錯(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腳本。

代碼

  • 效果實(shí)現(xiàn)

  • 代碼
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ò),歡迎將生活随笔推薦給好友。