zoukankan      html  css  js  c++  java
  • [转] 主流JS框架中DOMReady事件的实现

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

    1. Prototype
    2. jQeury
    3. moontools
    4. dojo
    5. yui
    6. 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 var timer;
    5 function fireContentLoadedEvent() {
    6 if (document.loaded) return;
    7 if (timer) window.clearInterval(timer);
    8 document.fire("dom:loaded");
    9 document.loaded = true;
    10 }
    11 if (document.addEventListener) {
    12 if (Prototype.Browser.WebKit) {
    13 timer = window.setInterval(function() {
    14 if (/loaded|complete/.test(document.readyState))
    15 fireContentLoadedEvent();
    16 }, 0);
    17 Event.observe(window, "load", fireContentLoadedEvent);
    18 } else {
    19 document.addEventListener("DOMContentLoaded",
    20 fireContentLoadedEvent, false);
    21 }
    22 } else {
    23 document.write("<"+"script id=__onDOMContentLoaded defer src=//:><\/script>");
    24 $("__onDOMContentLoaded").onreadystatechange = function() {
    25 if (this.readyState == "complete") {
    26 this.onreadystatechange = null;
    27 fireContentLoadedEvent();
    28 }
    29 };
    30 }
    31 })();

    实现思路如下:

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

    实现思路如下:

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

    三、Moontools

    1 (function(){
    2 var domready = function(){
    3 if (Browser.loaded) return;
    4 Browser.loaded = true;
    5 window.fireEvent('domready');
    6 document.fireEvent('domready');
    7 };
    8 if (Browser.Engine.trident){
    9 var temp = document.createElement('div');
    10 (function(){
    11 ($try(function(){
    12 temp.doScroll('left');
    13 return $(temp).inject(document.body).set('html', 'temp').dispose();
    14 })) ? domready() : arguments.callee.delay(50);
    15 })();
    16 } else if (Browser.Engine.webkit && Browser.Engine.version < 525){
    17 (function(){
    18 (['loaded', 'complete'].contains(document.readyState)) ? domready() : arguments.callee.delay(50);
    19 })();
    20 } else {
    21 window.addEvent('load', domready);
    22 document.addEvent('DOMContentLoaded', domready);
    23 }
    24 })();

    实现思路如下:

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

    实现思路如下:

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

    五、YUI

    1 (function() {
    2 /*! DOMReady: based on work by: Dean Edwards/John Resig/Matthias Miller */
    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 // Process onAvailable/onContentReady items when the
    9 // DOM is ready.
    10 YAHOO.util.Event.onDOMReady(
    11 YAHOO.util.Event._tryPreloadAttach,
    12 YAHOO.util.Event, true);
    13 var n = document.createElement('p');
    14 EU._dri = setInterval(function() {
    15 try {
    16 // throws an error if doc is not ready
    17 n.doScroll('left');
    18 clearInterval(EU._dri);
    19 EU._dri = null;
    20 EU._ready();
    21 n = null;
    22 } catch (ex) {
    23 }
    24 }, EU.POLL_INTERVAL);
    25 // The document's readyState in Safari currently will
    26 // change to loaded/complete before images are loaded.
    27 } else if (EU.webkit && EU.webkit < 525) {
    28 EU._dri = setInterval(function() {
    29 var rs=document.readyState;
    30 if ("loaded" == rs || "complete" == rs) {
    31 clearInterval(EU._dri);
    32 EU._dri = null;
    33 EU._ready();
    34 }
    35 }, EU.POLL_INTERVAL);
    36 // FireFox and Opera: These browsers provide a event for this
    37 // moment. The latest WebKit releases now support this event.
    38 } else {
    39 EU._simpleAdd(document, "DOMContentLoaded", EU._ready);
    40 }
    41 /////////////////////////////////////////////////////////////
    42 EU._simpleAdd(window, "load", EU._load);
    43 EU._simpleAdd(window, "unload", EU._unload);
    44 EU._tryPreloadAttach();
    45 })();

    实现思路与Moontools一样

    六、EXT

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

    实现思路与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 = {
    11 enableMozDOMReady:true
    12 };
    13 if( config )
    14 for( var p in config)
    15 this.conf[p] = config[p];
    16 var isReady = false;
    17 function doReady(){
    18 if( isReady ) return;
    19 //确保onready只执行一次
    20 isReady = true;
    21 onready();
    22 }
    23 /*IE*/
    24 if( Browser.ie ){
    25 (function(){
    26 if ( isReady ) return;
    27 try {
    28 document.documentElement.doScroll("left");
    29 } catch( error ) {
    30 setTimeout( arguments.callee, 0 );
    31 return;
    32 }
    33 doReady();
    34 })();
    35 window.attachEvent('onload',doReady);
    36 }
    37 /*Webkit*/
    38 else if (Browser.webkit && Browser.version < 525){
    39 (function(){
    40 if( isReady ) return;
    41 if (/loaded|complete/.test(document.readyState))
    42 doReady();
    43 else
    44 setTimeout( arguments.callee, 0 );
    45 })();
    46 window.addEventListener('load',doReady,false);
    47 }
    48 /*FF Opera 高版webkit 其他*/
    49 else{
    50 if( !Browser.ff || Browser.version != 2 || this.conf.enableMozDOMReady)
    51 document.addEventListener( "DOMContentLoaded", function(){
    52 document.removeEventListener( "DOMContentLoaded", arguments.callee, false );
    53 doReady();
    54 }, false );
    55 window.addEventListener('load',doReady,false);
    56 }
    57 }

  • 相关阅读:
    OC编程之道-创建对象之工厂方法
    OC编程之道-创建对象之单例模式
    OC编程之道-创建对象之原型模式
    OC编程之道-创建对象之生成器模式
    effective OC2.0 52阅读笔记(七 系统框架)
    effective OC2.0 52阅读笔记(六 块)+ Objective-C高级编程 (二 Blocks)
    effective OC2.0 52阅读笔记(五 内存管理)
    effective OC2.0 52阅读笔记(四 协议与分类)
    安装Sublime Text 3插件的方法
    cocos2d-x学习笔记
  • 原文地址:https://www.cnblogs.com/JulyZhang/p/1952484.html
Copyright © 2011-2022 走看看