主流JS框架中DOMReady事件的實現

在實際應用中,咱們常常會遇到這樣的場景,當頁面加載完成後去作一些事情:綁定事件、DOM操做某些結點等。原來比較經常使用的是window的onload 事件,而該事件的實際效果是:當頁面解析/DOM樹創建完成,並完成了諸如圖片、腳本、樣式表甚至是iframe中全部資源的下載後才觸發的。這對於不少 實際的應用而言有點太「遲」了,比較影響用戶體驗。爲了解決這個問題,ff中便增長了一個DOMContentLoaded方法,與onload相比,該 方法觸發的時間更早,它是在頁面的DOM內容加載完成後即觸發,而無需等待其餘資源的加載。Webkit引擎從版本525(Webkit nightly 1/2008:525+)開始也引入了該事件,Opera中也包含該方法。到目前爲止主流的IE仍然沒有要添加的意思。雖然IE下沒有,但老是有解決辦法 的,下文對比了一下幾大主流框架對於該事件的兼容性版本實現方案,涉及的框架包括: javascript

  1. Prototype
  2. jQeury
  3. moontools
  4. dojo
  5. yui
  6. ext

1、Prototype

實現代碼: html

(function () {
	/* Support for the DOMContentLoaded event is based on work by Dan Webb,
	Matthias Miller, Dean Edwards and John Resig. */
	var timer;
	function fireContentLoadedEvent() {
		if (document.loaded)
			return;
		if (timer)
			window.clearInterval(timer);
		document.fire("dom:loaded");
		document.loaded = true;
	}
	if (document.addEventListener) {
		if (Prototype.Browser.WebKit) {
			timer = window.setInterval(function () {
					if (/loaded|complete/.test(document.readyState))
						fireContentLoadedEvent();
				}, 0);
			Event.observe(window, "load", fireContentLoadedEvent);
		} else {
			document.addEventListener("DOMContentLoaded",
				fireContentLoadedEvent, false);
		}
	} else {
		document.write("<" + "script id=__onDOMContentLoaded defer src=//:><\/script>");
		$("__onDOMContentLoaded").onreadystatechange = function () {
			if (this.readyState == "complete") {
				this.onreadystatechange = null;
				fireContentLoadedEvent();
			}
		};
	}
})();

實現思路以下: java

  1. 若是是webkit則輪詢document的readyState屬性,若是該屬性的值爲loaded或complete則觸發DOMContentLoaded事件,爲保險起見,將該事件註冊到window.onload上。
  2. 若是是FF則直接註冊DOMContentLoaded事件。
  3. 若是是IE則使用document.write往頁面中加入一個script元素,並設置defer屬性,最後是把該腳本的加載完成視做DOMContentLoaded事件來觸發。

該實現方式的問題主要有兩點:第1、經過document.write寫script並設置defer的方法在頁面包含iframe的狀況下,會等到 iframe內的內容加載完後才觸發,這與onload沒有太大的區別;第2、Webkit在525以上的版本引入了DOMContentLoaded方 法,所以在這些版本中無需再經過輪詢來實現,能夠優化。 node

2、jQuery

function bindReady() {
	if (readyBound)
		return;
	readyBound = true;
	// Mozilla, Opera and webkit nightlies currently support this event
	if (document.addEventListener) {
		// Use the handy event callback
		document.addEventListener("DOMContentLoaded", function () {
			document.removeEventListener("DOMContentLoaded", arguments.callee, false);
			jQuery.ready();
		}, false);
		// If IE event model is used
	} else if (document.attachEvent) {
		// ensure firing before onload,
		// maybe late but safe also for iframes
		document.attachEvent("onreadystatechange", function () {
			if (document.readyState === "complete") {
				document.detachEvent("onreadystatechange", arguments.callee);
				jQuery.ready();
			}
		});
		// If IE and not an iframe
		// continually check to see if the document is ready
		if (document.documentElement.doScroll && typeof window.frameElement === "undefined")
			(function () {
				if (jQuery.isReady)
					return;
				try {
					// If IE is used, use the trick by Diego Perini
					// http://javascript.nwbox.com/IEContentLoaded/
					document.documentElement.doScroll("left");
				} catch (error) {
					setTimeout(arguments.callee, 0);
					return;
				}
				// and execute any waiting functions
				jQuery.ready();
			})();
	}
	// A fallback to window.onload, that will always work
	jQuery.event.add(window, "load", jQuery.ready);
}

實現思路以下: web

  1. 將Webkit與Firefox同等對待,都是直接註冊DOMContentLoaded事件,可是因爲Webkit是在525以上版本才引入的,所以存在兼容性的隱患。
  2. 對於IE,首先註冊document的onreadystatechange事件,經測試,該方式與window.onload至關,依然會等到全部資源下載完畢後才觸發。
  3. 以後,判斷若是是IE而且頁面不在iframe當中,則經過setTiemout來不斷的調用documentElement的doScroll方法,直到調用成功則出觸發DOMContentLoaded

jQuery對於IE的解決方案,使用了一種新的方法,該方法源自http://javascript.nwbox.com/IEContentLoaded/。 它的原理是,在IE下,DOM的某些方法只有在DOM解析完成後才能夠調用,doScroll就是這樣一個方法,反過來當能調用doScroll的時候即 是DOM解析完成之時,與prototype中的document.write相比,該方案能夠解決頁面有iframe時失效的問題。此外,jQuery 彷佛擔憂當頁面處於iframe中時,該方法會失效,所以實現代碼中作了判斷,若是是在iframe中則經過document的 onreadystatechange來實現,不然經過doScroll來實現。不過經測試,即便是在iframe中,doScroll依然有效。 瀏覽器

3、Moontools

(function () {
	var domready = function () {
		if (Browser.loaded)
			return;
		Browser.loaded = true;
		window.fireEvent('domready');
		document.fireEvent('domready');
	};
	if (Browser.Engine.trident) {
		var temp = document.createElement('div');
		(function () {
			($try(function () {
					temp.doScroll('left');
					return $(temp).inject(document.body).set('html', 'temp').dispose();
				})) ? domready() : arguments.callee.delay(50);
		})();
	} else if (Browser.Engine.webkit && Browser.Engine.version < 525) {
		(function () {
			(['loaded', 'complete'].contains(document.readyState)) ? domready() : arguments.callee.delay(50);
		})();
	} else {
		window.addEvent('load', domready);
		document.addEvent('DOMContentLoaded', domready);
	}
})();

實現思路以下: app

  1. 若是是IE則使用doScroll方法來實現。
  2. 若是是小於525版本的Webkit則經過輪詢document.readyState來實現。
  3. 其餘的(FF/Webkit高版/Opera)則直接註冊DOMContentLoaded事件

Moontools的實現方案prototype和jQeury中的綜合體,對webkit作了版本判斷則使得該方案更加的健壯。在doScroll的實現方面,與jQuery相比,這裏是新建了一個div元素,而且在使用完畢後進行銷燬,而jQuery則直接使用了documentElement的 doScroll來檢測,更簡單高效一些。 框架

4、Dojo

// START DOMContentLoaded
// Mozilla and Opera 9 expose the event we could use
if (document.addEventListener) {
	// NOTE:
	//  due to a threading issue in Firefox 2.0, we can't enable
	//  DOMContentLoaded on that platform. For more information, see:
	//  http://trac.dojotoolkit.org/ticket/1704
	if (dojo.isOpera || dojo.isFF >= 3 || (dojo.isMoz && dojo.config.enableMozDomContentLoaded === true)) {
		document.addEventListener("DOMContentLoaded", dojo._loadInit, null);
	}
	// mainly for Opera 8.5, won't be fired if DOMContentLoaded fired already.
	//  also used for Mozilla because of trac #1640
	window.addEventListener("load", dojo._loadInit, null);
}
if (dojo.isAIR) {
	window.addEventListener("load", dojo._loadInit, null);
} else if (/(WebKit|khtml)/i.test(navigator.userAgent)) { // sniff
	dojo._khtmlTimer = setInterval(function () {
			if (/loaded|complete/.test(document.readyState)) {
				dojo._loadInit(); // call the onload handler
			}
		}, 10);
}
// END DOMContentLoaded
}
(function () {
	var _w = window;
	var _handleNodeEvent = function (/*String*/
		evtName, /*Function*/
		fp) {
		// summary:
		//  non-destructively adds the specified function to the node's
		//  evtName handler.
		// evtName: should be in the form "onclick" for "onclick" handlers.
		// Make sure you pass in the "on" part.
		var oldHandler = _w[evtName] || function () {};
		_w[evtName] = function () {
			fp.apply(_w, arguments);
			oldHandler.apply(_w, arguments);
		};
	};
	if (dojo.isIE) {
		//  for Internet Explorer. readyState will not be achieved on init
		//  call, but dojo doesn't need it however, we'll include it
		//  because we don't know if there are other functions added that
		//  might.  Note that this has changed because the build process
		//  strips all comments -- including conditional ones.
		if (!dojo.config.afterOnLoad) {
			document.write('<scr' + 'ipt defer="" src="//:" +="" onreadystatechange="if(this.readyState==\'complete\'){' + dojo._scopeName + '._loadInit();}">'
				 + '</scr' + 'ipt>');
		}
		try {
			document.namespaces.add("v", "urn:schemas-microsoft-com:vml");
			document.createStyleSheet().addRule("v\\:*", "behavior:url(#default#VML)");
		} catch (e) {}
	}
	// FIXME: dojo.unloaded requires dojo scope, so using anon function wrapper.
	_handleNodeEvent("onbeforeunload", function () {
		dojo.unloaded();
	});
	_handleNodeEvent("onunload", function () {
		dojo.windowUnloaded();
	});
})();

實現思路以下: dom

  1. 若是是Opera或FF3以上版本則直接註冊DOMContentLoaded<事件,爲保險起見,同時也註冊了window.onload事件。
  2. 對於webkit則經過輪詢document.readyState來實現。
  3. 若是是Air則只註冊widnow.onload事件。
  4. 若是是IE則經過往頁面寫帶defer屬性的script並註冊其onreadystatechange事件來實現。

Dojo在IE下的實現方案一樣沒法解決iframe的問題,而因爲在FF2 下會有一個很是奇怪的Bug,所以默認只在FF3以上版本上使用DOMContentLoaded事件,同時又給了一個配置 -dojo.config.enableMozDomContentLoaded,若是在FF下將該配置設置爲true則依然會使用 DOMContentLoaded來實現,這一點充分考慮到了靈活性。對於webkit的實現,與prototype同樣有優化的空間。 ide

5、YUI

/*! DOMReady: based on work by: Dean Edwards/John Resig/Matthias Miller */
// Internet Explorer: use the readyState of a defered script.
// This isolates what appears to be a safe moment to manipulate
// the DOM prior to when the document's readyState suggests
// it is safe to do so.
if (EU.isIE) {
	// Process onAvailable/onContentReady items when the
	// DOM is ready.
	YAHOO.util.Event.onDOMReady(
		YAHOO.util.Event._tryPreloadAttach,
		YAHOO.util.Event, true);
	var n = document.createElement('p');
	EU._dri = setInterval(function () {
			try {
				// throws an error if doc is not ready
				n.doScroll('left');
				clearInterval(EU._dri);
				EU._dri = null;
				EU._ready();
				n = null;
			} catch (ex) {}
		}, EU.POLL_INTERVAL);
	// The document's readyState in Safari currently will
	// change to loaded/complete before images are loaded.
} else if (EU.webkit && EU.webkit < 525) {
	EU._dri = setInterval(function () {
			var rs = document.readyState;
			if ("loaded" == rs || "complete" == rs) {
				clearInterval(EU._dri);
				EU._dri = null;
				EU._ready();
			}
		}, EU.POLL_INTERVAL);
	// FireFox and Opera: These browsers provide a event for this
	// moment.  The latest WebKit releases now support this event.
} else {
	EU._simpleAdd(document, "DOMContentLoaded", EU._ready);
}
/////////////////////////////////////////////////////////////
EU._simpleAdd(window, "load", EU._load);
EU._simpleAdd(window, "unload", EU._unload);
EU._tryPreloadAttach();
})();

實現思路與Moontools同樣

6、EXT

function initDocReady() {
	var COMPLETE = "complete";
	docReadyEvent = new Ext.util.Event();
	if (Ext.isGecko || Ext.isOpera) {
		DOC.addEventListener(DOMCONTENTLOADED, fireDocReady, false);
	} else if (Ext.isIE) {
		DOC.write("<s" + 'cript id=" + IEDEFERED + " defer="defer" src="/%27+%27/:"></s"+' cript > ");
		DOC.getElementById(IEDEFERED).onreadystatechange = function(){
			if(this.readyState == COMPLETE){
				fireDocReady();
			}
		};
	} else if (Ext.isWebKit){
		docReadyProcId = setInterval(function(){
			if(DOC.readyState == COMPLETE) {
				fireDocReady();
			}
		}, 10);
	}
	// no matter what, make sure it fires on load
	E.on(WINDOW, " load ", fireDocReady);
};

實現思路與Dojo的一致,再也不贅訴。

總結

總結各大主流框架的作法,寫了如下這個版本。主要是儘可能的作到優化並考慮到FF2下的Bug,提供一個是否使用DOMContentLoaded的開關配置。

/*
 * 註冊瀏覽器的DOMContentLoaded事件
 * @param { Function } onready [必填]在DOMContentLoaded事件觸發時須要執行的函數
 * @param { Object } config [可選]配置項
 */
function onDOMContentLoaded(onready, config) {
	//瀏覽器檢測相關對象,在此爲節省代碼未實現,實際使用時須要實現。
	//var Browser = {};
	//設置是否在FF下使用DOMContentLoaded(在FF2下的特定場景有Bug)
	this.conf = {
		enableMozDOMReady : true
	};
	if (config)
		for (var p in config)
			this.conf[p] = config[p];
	var isReady = false;
	function doReady() {
		if (isReady)
			return;
		//確保onready只執行一次
		isReady = true;
		onready();
	}
	/*IE*/
	if (Browser.ie) {
		(function () {
			if (isReady)
				return;
			try {
				document.documentElement.doScroll("left");
			} catch (error) {
				setTimeout(arguments.callee, 0);
				return;
			}
			doReady();
		})();
		window.attachEvent('onload', doReady);
	}
	/*Webkit*/
	else if (Browser.webkit && Browser.version < 525) {
		(function () {
			if (isReady)
				return;
			if (/loaded|complete/.test(document.readyState))
				doReady();
			else
				setTimeout(arguments.callee, 0);
		})();
		window.addEventListener('load', doReady, false);
	}
	/*FF Opera 高版webkit 其餘*/
	else {
		if (!Browser.ff || Browser.version != 2 || this.conf.enableMozDOMReady)
			document.addEventListener("DOMContentLoaded", function () {
				document.removeEventListener("DOMContentLoaded", arguments.callee, false);
				doReady();
			}, false);
		window.addEventListener('load', doReady, false);
	}
}
相關文章
相關標籤/搜索