實現頁面異步加載


應用場景

平時我們用的最多的網頁加載方式就是同步加載模式,也稱阻塞模式,這種模式雖然安全,但是對於設計比較繁瑣的網頁采用同步加載會使網頁的加載時間大大加長,所以也就出現了下面用到的異步加載模式。

使用

異步加載可以使用 XHR Injection、 XHR Eval、 Script In Iframe、 Script defer屬性、 document.write(script tag)等,我當前采用的的是Script DOM Element方法,也就是動態向頁面創建script標簽異步加載JS腳本。

代碼

  • 效果實現

image

  • 代碼
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) { //IE
			script.onreadystatechange = function() {
				if(script.readyState == "loaded" || script.readyState == "complete") {
					script.onreadystatechange = null;
					if(callback) callback()
				}
			};
		} else { //Others
			script.onload = function() {
				if(callback) callback()
			}
		}
		document.getElementsByTagName("body")[0].appendChild(script);
	}
}
init.initSwitch()

原理實現

主要原理就是首次加載只加載所需腳本文件,首次切換其他頁面時,動態加載所需腳本,並標識已加載防止重復加載,異步回調方法可以在腳本加載完成時執行相關操作。

注意

如果調用的JS內容存在下面兩種情況都會報錯:

在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. “
  1. js調用 了document.write
  2. 或者通過js 自動創建script標簽加載內容

GitHub 源文件

https://github.com/lizhixuan1/JavaScript/tree/Async-Load


需要的朋友可以參考,如有不足,歡迎交流評論


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM