More fun with DOMContentLoaded

Written by on September 26th, 2007 in Ajax News.

It is amazing how much chatter we have about wanting to know when the darn DOM is ready, and finding the right place to start doing your work. We just posted about IEContentLoaded and already Stuart Langridge has taken that and the other approaches and come up with this 7 liner (if you aren’t using a library that already does it for you):

JAVASCRIPT:

  1.  
  2. (function(i) {var u =navigator.userAgent;var e=/*@cc_on!@*/false; var st =
  3. setTimeout;if(/webkit/i.test(u)){st(function(){var dr=document.readyState;
  4. if(dr==”loaded”||dr==”complete”){i()}else{st(arguments.callee,10);}},10);}
  5. else if((/mozilla/i.test(u)&&!/(compati)/.test(u)) || (/opera/i.test(u))){
  6. document.addEventListener(”DOMContentLoaded”,i,false); } else if(e){     (
  7. function(){var t=document.createElement(’doc:rdy’);try{t.doScroll(’left’);
  8. i();t=null;}catch(e){st(arguments.callee,0);}})();}else{window.onload=i;}})(YOUR_FUNCTION);
  9.  

John Resig is taking jQuery in a different direction though:

I have another technique that I posted to the list a while back, that I’ll be switching jQuery to. If you attempt to insert into the document.body before the document is fully loaded, an exception is thrown. I take advantage of that to determine when the document is fully loaded. I like that particular technique better because it actually tells you when you can manipulate the DOM - as opposed to this scroll thing which may, or may not, correspond to the document being loaded.

Source: Ajaxian
Original Article: http://feeds.feedburner.com/~r/ajaxian/~3/161588330/more-fun-with-domcontentloaded

Leave a Reply

You must be logged in to post a comment.



Site Navigation