JSDOMReady事件的六種實現方法總結

來源:互聯網
上載者:User
在實際應用中,我們經常會遇到這樣的情境,當頁面載入完成後去做一些事情:綁定事件、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

實現代碼

(function() { 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(); } }; } })();

實現思路如下:

如果是webkit則輪詢document的readyState屬性,如果該屬性的值為loaded或complete則觸發DOMContentLoaded事件,為保險起見,將該事件註冊到window.onload上。

如果是FF則直接註冊DOMContentLoaded事件。

如果是IE則使用document.write往頁面中加入一個script元素,並設定defer屬性,最後是把該指令碼的載入完成視作DOMContentLoaded事件來觸發。

該實現方式的問題主要有兩點:第一、通過document.write寫script並設定defer的方法在頁麵包含iframe的情況下,會等到 iframe內的內容載入完後才觸發,這與onload沒有太大的區別;第二、Webkit在525以上的版本引入了DOMContentLoaded方法,因此在這些版本中無需再通過輪詢來實現,可以最佳化。

二、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 ); }

實現思路如下:

將Webkit與Firefox同等對待,都是直接註冊DOMContentLoaded事件,但是由於Webkit是在525以上版本才引入的,因此存在相容性的隱患。

對於IE,首先註冊document的onreadystatechange事件,經測試,該方式與window.onload相當,依然會等到所有資源下載完畢後才觸發。

之後,判斷如果是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

(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_x('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);  }  })();

四、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(evtName, 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(); });  })();

實現思路如下:

如果是Opera或FF3以上版本則直接註冊DOMContentLoaded<事件,為保險起見,同時也註冊了window.onload事件。

對於webkit則通過輪詢document.readyState來實現。

如果是Air則只註冊widnow.onload事件。

如果是IE則通過往頁面寫帶defer屬性的script並註冊其onreadystatechange事件來實現。

Dojo在IE下的實現方案同樣無法解決iframe的問題,而由於在FF2 下會有一個非常奇怪的Bug,因此預設只在FF3以上版本上使用DOMContentLoaded事件,同時又給了一個配置 -dojo.config.enableMozDomContentLoaded,如果在FF下將該配置設定為true則依然會使用 DOMContentLoaded來實現,這一點充分考慮到了靈活性。對於webkit的實現,與prototype一樣有最佳化的空間。

五、YUI

// 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_x('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一樣

六、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="/'+'/:"></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的開關配置。

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();  }    if( Browser.ie ){  (function(){  if ( isReady ) return;  try {  document.documentElement.doScroll("left");  } catch( error ) {  setTimeout( arguments.callee, 0 );  return;  }  doReady();  })();  window.attachEvent('onload',doReady);  }    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);  }    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);  }  }

以上這篇JS DOMReady事件的六種實現方法總結就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援topic.alibabacloud.com。

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.