转流框架中DOMContentLoaded事件的实现 简单

转自:http://www.ipmtea.net/jquery/201009/27_308.html

//PS: 部分代码仅供参考,jquery的实现似乎有bug

//参考最新jquery实现

在实际应用中,我们经常会遇到这样的场景,当页面加载完成后去做一些事情:绑定事件、DOM操作某些结点等。原来比较常用的是window的onload事件,而该事件的实际效果是:当页面解析/DOM树建立完成,并完成了诸如图片、脚本、样式表甚至是iframe中所有资源的下载后才触发的。这对于很多实际的应用而言有点太“迟”了,比较影响用户体验。为了解决这个问题,FF中便增加了一个DOMContentLoaded方法,与onload相比,该方法触发的时间更早,它是在页面的DOM内容加载完成后即触发,而无需等待其他资源的加载。Webkit引擎从版本525(Webkit nightly 1/2008:525+)开始也引入了该事件,Opera中也包含该方法。到目前为止主流的IE仍然没有要添加的意思。虽然IE下没有,但总是有解决办法的,下文对比了一下几大主流框架对于该事件的兼容性版本实现方案,涉及的框架包括:

  • Prototype
  • jQeury
  • moontools
  • dojo
  • yui
  • ext

     

一、Prototype

实现代码

  1. (function() {     
  2.   /* Support for the DOMContentLoaded event is based on work by Dan Webb,    
  3.      Matthias Miller, Dean Edwards and John Resig. */    
  4.     
  5.   var timer;     
  6.     
  7.   function fireContentLoadedEvent() {     
  8.     if (document.loaded) return;     
  9.     if (timer) window.clearInterval(timer);     
  10.     document.fire("dom:loaded");     
  11.     document.loaded = true;     
  12.   }     
  13.     
  14.   if (document.addEventListener) {     
  15.     if (Prototype.Browser.WebKit) {     
  16.       timer = window.setInterval(function() {     
  17.         if (/loaded|complete/.test(document.readyState))     
  18.           fireContentLoadedEvent();     
  19.       }, 0);     
  20.     
  21.       Event.observe(window, "load", fireContentLoadedEvent);     
  22.     
  23.     } else {     
  24.       document.addEventListener("DOMContentLoaded",     
  25.         fireContentLoadedEvent, false);     
  26.     }     
  27.     
  28.   } else {     
  29.     document.write("<"+"script id=__onDOMContentLoaded defer src=//:><\/script>");     
  30.     $("__onDOMContentLoaded").onreadystatechange = function() {     
  31.       if (this.readyState == "complete") {     
  32.         this.onreadystatechange = null;     
  33.         fireContentLoadedEvent();     
  34.       }     
  35.     };     
  36.   }     
  37. })();    

实现思路如下:

1、如果是webkit则轮询document的readyState属性,如果该属性的值为loaded或complete则触发DOMContentLoaded事件,为保险起见,将该事件注册到window.onload上。

2、如果是FF则直接注册DOMContentLoaded事件。

3、如果是IE则使用document.write往页面中加入一个script元素,并设置defer属性,最后是把该脚本的加载完成视作DOMContentLoaded事件来触发。

该实现方式的问题主要有两点:第一、通过document.write写script并设置defer的方法在页面包含iframe的情况下,会等到iframe内的内容加载完后才触发,这与onload没有太大的区别;第二、Webkit在525以上的版本引入了DOMContentLoaded方法,因此在这些版本中无需再通过轮询来实现,可以优化。

二、jQuery

  1. function bindReady(){     
  2.     if ( readyBound ) return;     
  3.     readyBound = true;     
  4.     
  5.     // Mozilla, Opera and webkit nightlies currently support this event     
  6.     if ( document.addEventListener ) {     
  7.         // Use the handy event callback     
  8.         document.addEventListener( "DOMContentLoaded"function(){     
  9.             document.removeEventListener( "DOMContentLoaded", arguments.callee, false );     
  10.             jQuery.ready();     
  11.         }, false );     
  12.     
  13.     // If IE event model is used     
  14.     } else if ( document.attachEvent ) {     
  15.         // ensure firing before onload,     
  16.         // maybe late but safe also for iframes     
  17.         document.attachEvent("onreadystatechange"function(){     
  18.             if ( document.readyState === "complete" ) {     
  19.                 document.detachEvent( "onreadystatechange", arguments.callee );     
  20.                 jQuery.ready();     
  21.             }     
  22.         });     
  23.     
  24.         // If IE and not an iframe     
  25.         // continually check to see if the document is ready     
  26.         if ( document.documentElement.doScroll && typeof window.frameElement === "undefined" ) 
  27. (function(){     
  28.             if ( jQuery.isReady ) return;     
  29.     
  30.             try {     
  31.                 // If IE is used, use the trick by Diego Perini     
  32.                 // http://javascript.nwbox.com/IEContentLoaded/     
  33.                 document.documentElement.doScroll("left");     
  34.             } catch( error ) {     
  35.                 setTimeout( arguments.callee, 0 );     
  36.                 return;     
  37.             }     
  38.     
  39.             // and execute any waiting functions     
  40.             jQuery.ready();     
  41.         })();     
  42.     }     
  43.     
  44.     // A fallback to window.onload, that will always work     
  45.     jQuery.event.add( window, "load", jQuery.ready );     
  46. }   

实现思路如下:

1、将Webkit与Firefox同等对待,都是直接注册DOMContentLoaded事件,但是由于Webkit是在525以上版本才引入的,因此存在兼容性的隐患。

2、对于IE,首先注册document的onreadystatechange事件,经测试,该方式与window.onload相当,依然会等到所有资源下载完毕后才触发。

3、之后,判断如果是IE并且页面不在iframe当中,则通过setTiemout来不断的调用documentElement的doScroll方法,直到调用成功则出触发DOMContentLoaded。1

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依然有效。

 

 

三、Moontools

 //最新版本

//1.4.5

(function(window, document){

var ready,
	loaded,
	checks = [],
	shouldPoll,
	timer,
	testElement = document.createElement('div');

var domready = function(){
	clearTimeout(timer);
	if (ready) return;
	Browser.loaded = ready = true;
	document.removeListener('DOMContentLoaded', domready).removeListener('readystatechange', check);

	document.fireEvent('domready');
	window.fireEvent('domready');
};

var check = function(){
	for (var i = checks.length; i--;) if (checks[i]()){
		domready();
		return true;
	}
	return false;
};

var poll = function(){
	clearTimeout(timer);
	if (!check()) timer = setTimeout(poll, 10);
};

document.addListener('DOMContentLoaded', domready);

/**/
// doScroll technique by Diego Perini http://javascript.nwbox.com/IEContentLoaded/
// testElement.doScroll() throws when the DOM is not ready, only in the top window
var doScrollWorks = function(){
	try {
		testElement.doScroll();
		return true;
	} catch (e){}
	return false;
};
// If doScroll works already, it can't be used to determine domready
//   e.g. in an iframe
if (testElement.doScroll && !doScrollWorks()){
	checks.push(doScrollWorks);
	shouldPoll = true;
}
/**/

if (document.readyState) checks.push(function(){
	var state = document.readyState;
	return (state == 'loaded' || state == 'complete');
});

if ('onreadystatechange' in document) document.addListener('readystatechange', check);
else shouldPoll = true;

if (shouldPoll) poll();

Element.Events.domready = {
	onAdd: function(fn){
		if (ready) fn.call(this);
	}
};

// Make sure that domready fires before load
Element.Events.load = {
	base: 'load',
	onAdd: function(fn){
		if (loaded && this == window) fn.call(this);
	},
	condition: function(){
		if (this == window){
			domready();
			delete Element.Events.load;
		}
		return true;
	}
};

// This is based on the custom load event
window.addEvent('load', function(){
	loaded = true;
});

})(window, document);

实现思路如下:

1、如果是IE则使用doScroll方法来实现。

2、如果是小于525版本的Webkit则通过轮询document.readyState来实现。

3、其他的(FF/Webkit高版/Opera)则直接注册DOMContentLoaded事件。

Moontools的实现方案prototype和jQeury中的综合体,对webkit做了版本判断则使得该方案更加的健壮。在doScroll的实现方面,与jQuery相比,这里是新建了一个div元素,并且在使用完毕后进行销毁,而jQuery则直接使用了documentElement的doScroll来检测,更简单高效一些。

 

 

 

四、Dojo

  1. //  START DOMContentLoaded     
  2.         // Mozilla and Opera 9 expose the event we could use     
  3.         if(document.addEventListener){     
  4.             // NOTE:     
  5.             //      due to a threading issue in Firefox 2.0, we can't enable     
  6.             //      DOMContentLoaded on that platform. For more information, see:     
  7.             //      http://trac.dojotoolkit.org/ticket/1704     
  8.             if(dojo.isOpera || dojo.isFF >= 3 || (dojo.isMoz && dojo.config.enableMozDomContentLoaded === true)){     
  9.                 document.addEventListener("DOMContentLoaded", dojo._loadInit, null);     
  10.             }     
  11.     
  12.             //  mainly for Opera 8.5, won't be fired if DOMContentLoaded fired already.     
  13.             //  also used for Mozilla because of trac #1640     
  14.             window.addEventListener("load", dojo._loadInit, null);     
  15.         }     
  16.     
  17.         if(dojo.isAIR){     
  18.             window.addEventListener("load", dojo._loadInit, null);     
  19.         }else if(/(WebKit|khtml)/i.test(navigator.userAgent)){ // sniff     
  20.             dojo._khtmlTimer = setInterval(function(){     
  21.                 if(/loaded|complete/.test(document.readyState)){     
  22.                     dojo._loadInit(); // call the onload handler     
  23.                 }     
  24.             }, 10);     
  25.         }     
  26.         //  END DOMContentLoaded     
  27.     }     
  28.     
  29.     (function(){     
  30.         var _w = window;     
  31.         var _handleNodeEvent = function(/*String*/evtName, /*Function*/fp){     
  32.             // summary:     
  33.             //      non-destructively adds the specified function to the node's     
  34.             //      evtName handler.     
  35.             // evtName: should be in the form "onclick" for "onclick" handlers.     
  36.             // Make sure you pass in the "on" part.     
  37.             var oldHandler = _w[evtName] || function(){};     
  38.             _w[evtName] = function(){     
  39.                 fp.apply(_w, arguments);     
  40.                 oldHandler.apply(_w, arguments);     
  41.             };     
  42.         };     
  43.     
  44.         if(dojo.isIE){     
  45.             //  for Internet Explorer. readyState will not be achieved on init     
  46.             //  call, but dojo doesn't need it however, we'll include it     
  47.             //  because we don't know if there are other functions added that     
  48.             //  might.  Note that this has changed because the build process     
  49.             //  strips all comments -- including conditional ones.     
  50.             if(!dojo.config.afterOnLoad){     
  51.                 document.write('<SCR'+'IPT ?onreadystatechange="if(this.readyState==\'complete\'){' + dojo._scopeName + '._loadInit();}" + ? src="//:" defer>'    
  52.                     + '</SCR'+'IPT>'    
  53.                 );     
  54.             }     
  55.     
  56.             try{     
  57.                 document.namespaces.add("v","urn:schemas-microsoft-com:vml");     
  58.                 document.createStyleSheet().addRule("v\\:*""behavior:url(#default#VML)");     
  59.             }catch(e){}     
  60.         }     
  61.     
  62.         // FIXME: dojo.unloaded requires dojo scope, so using anon function wrapper.     
  63.         _handleNodeEvent("onbeforeunload"function() { dojo.unloaded(); });     
  64.         _handleNodeEvent("onunload"function() { dojo.windowUnloaded(); });     
  65.     })();  

实现思路如下:

1、如果是Opera或FF3以上版本则直接注册DOMContentLoaded<事件,为保险起见,同时也注册了window.onload事件。/li>

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一样有优化的空间。

五、YUI

  1. /*! DOMReady: based on work by: Dean Edwards/John Resig/Matthias Miller */    
  2.     
  3.         // Internet Explorer: use the readyState of a defered script.     
  4.         // This isolates what appears to be a safe moment to manipulate     
  5.         // the DOM prior to when the document's readyState suggests     
  6.         // it is safe to do so.     
  7.         if (EU.isIE) {     
  8.     
  9.             // Process onAvailable/onContentReady items when the     
  10.             // DOM is ready.     
  11.             YAHOO.util.Event.onDOMReady(     
  12.                     YAHOO.util.Event._tryPreloadAttach,     
  13.                     YAHOO.util.Event, true);     
  14.     
  15.             var n = document.createElement('p');      
  16.    
  17.             EU._dri = setInterval(function() {    
  18.                 try {    
  19.                     // throws an error if doc is not ready    
  20.                     n.doScroll('left');    
  21.                     clearInterval(EU._dri);    
  22.                     EU._dri = null;    
  23.                     EU._ready();    
  24.                     n = null;    
  25.                 } catch (ex) {    
  26.                 }    
  27.             }, EU.POLL_INTERVAL);     
  28.    
  29.         // The document's readyState in Safari currently will     
  30.         // change to loaded/complete before images are loaded.     
  31.         } else if (EU.webkit && EU.webkit < 525) {     
  32.     
  33.             EU._dri = setInterval(function() {     
  34.                 var rs=document.readyState;     
  35.                 if ("loaded" == rs || "complete" == rs) {     
  36.                     clearInterval(EU._dri);     
  37.                     EU._dri = null;     
  38.                     EU._ready();     
  39.                 }     
  40.             }, EU.POLL_INTERVAL);      
  41.     
  42.         // FireFox and Opera: These browsers provide a event for this     
  43.         // moment.  The latest WebKit releases now support this event.     
  44.         } else {     
  45.     
  46.             EU._simpleAdd(document, "DOMContentLoaded", EU._ready);     
  47.     
  48.         }     
  49.         /////////////////////////////////////////////////////////////     
  50.     
  51.         EU._simpleAdd(window, "load", EU._load);     
  52.         EU._simpleAdd(window, "unload", EU._unload);     
  53.         EU._tryPreloadAttach();     
  54.     })();  

实现思路与Moontools的一致,不再赘诉。

 

 

 

 

 

六、EXT

  1. function initDocReady(){     
  2.     var COMPLETE = "complete";     
  3.     
  4.     docReadyEvent = new Ext.util.Event();     
  5.     if (Ext.isGecko || Ext.isOpera) {     
  6.         DOC.addEventListener(DOMCONTENTLOADED, fireDocReady, false);     
  7.     } else if (Ext.isIE){     
  8.         DOC.write("<S"+'CRIPT id=" + IEDEFERED + " src="/'+'/:" defer="defer"></S'+"CRIPT>");     
  9.         DOC.getElementById(IEDEFERED).onreadystatechange = function(){     
  10.         if(this.readyState == COMPLETE){     
  11.             fireDocReady();     
  12.         }     
  13.         };     
  14.     } else if (Ext.isWebKit){     
  15.         docReadyProcId = setInterval(function(){     
  16.         if(DOC.readyState == COMPLETE) {     
  17.             fireDocReady();     
  18.          }     
  19.         }, 10);     
  20.     }     
  21.     // no matter what, make sure it fires on load     
  22.     E.on(WINDOW, "load", fireDocReady);     
  23. };    

实现思路与Dojo的一致,不再赘诉。

 

 

 

总结

总结各大主流框架的做法,写了以下这个版本。主要是尽量的做到优化并考虑到FF2下的Bug,提供一个是否使用DOMContentLoaded的开关配置。

  1. /*    
  2.  * 注册浏览器的DOMContentLoaded事件    
  3.  * @param { Function } onready [必填]在DOMContentLoaded事件触发时需要执行的函数    
  4.  * @param { Object } config [可选]配置项    
  5.  */    
  6. function onDOMContentLoaded(onready,config){     
  7.     //浏览器检测相关对象,在此为节省代码未实现,实际使用时需要实现。     
  8.     //var Browser = {};     
  9.     //设置是否在FF下使用DOMContentLoaded(在FF2下的特定场景有Bug)     
  10.     this.conf = {enableMozDOMReady:true};     
  11.     if( config )     
  12.     forvar p in config)     
  13.         this.conf[p] = config[p];     
  14.     
  15.     var isReady = false;     
  16.     function doReady(){     
  17.         if( isReady ) return;     
  18.         //确保onready只执行一次     
  19.         isReady = true;     
  20.         onready();     
  21.     }     
  22.     /*IE*/    
  23.     if( Browser.ie ){     
  24.         (function(){     
  25.             if ( isReady ) return;     
  26.             try {     
  27.                 document.documentElement.doScroll("left");     
  28.             } catch( error ) {     
  29.                 setTimeout( arguments.callee, 0 );     
  30.                 return;     
  31.             }     
  32.             doReady();     
  33.         })();     
  34.         window.attachEvent('onload',doReady);     
  35.     }     
  36.     /*Webkit*/    
  37.     else if (Browser.webkit && Browser.version < 525){     
  38.         (function(){     
  39.             if( isReady ) return;     
  40.             if (/loaded|complete/.test(document.readyState))     
  41.                 doReady();     
  42.             else    
  43.                 setTimeout( arguments.callee, 0 );     
  44.         })();     
  45.         window.addEventListener('load',doReady,false);     
  46.     }     
  47.     /*FF Opera 高版webkit 其他*/    
  48.     else{     
  49.         if( !Browser.ff || Browser.version != 2 || this.conf.enableMozDOMReady)     
  50.             document.addEventListener( "DOMContentLoaded"function(){     
  51.                 document.removeEventListener( "DOMContentLoaded", arguments.callee, false );     
  52.                 doReady();     
  53.             }, false );     
  54.         window.addEventListener('load',doReady,false);     
  55.     }     
  56.     
  57. }   
原文地址:https://www.cnblogs.com/chyong168/p/2535559.html