Your Ad Here

Posted By

freelancephp on 03/01/10


Tagged

event onload domready DOMContentLoaded IEContentLoaded


Versions (?)

DOMReady Object


 / Published in: JavaScript
 

URL: http://www.freelancephp.net/domready-javascript-object-cross-browser/

Small object for cross-browser compatibility of the DOMContentLoaded event. Easily add functions that will be executed when the DOM is ready.

  1. var DOMReady = (function () {
  2. var fns = [],
  3. isReady = false,
  4. ready = function () {
  5. isReady = true;
  6.  
  7. // call all functions
  8. for ( var x = 0; x < fns.length; x++ )
  9. fns[x]();
  10. };
  11.  
  12. // public add method
  13. this.add = function ( fn ) {
  14. // eval string in a function
  15. if ( fn.constructor == String ) {
  16. var strFunc = fn;
  17. fn = function () { eval( strFunc ); };
  18. }
  19.  
  20. // call imediately when DOM is already ready
  21. if ( isReady ) {
  22. fn();
  23. } else {
  24. // add to the list
  25. fns[fns.length] = fn;
  26. }
  27. };
  28.  
  29. // For all browsers except IE
  30. if ( window.addEventListener )
  31. document.addEventListener( 'DOMContentLoaded', function(){ ready(); }, false );
  32.  
  33. // For IE
  34. // Code taken from http://ajaxian.com/archives/iecontentloaded-yet-another-domcontentloaded
  35. (function(){
  36. // check IE's proprietary DOM members
  37. if ( ! document.uniqueID && document.expando ) return;
  38.  
  39. // you can create any tagName, even customTag like <document :ready />
  40. var tempNode = document.createElement('document:ready');
  41.  
  42. try {
  43. // see if it throws errors until after ondocumentready
  44. tempNode.doScroll('left');
  45.  
  46. // call ready
  47. ready();
  48. } catch ( err ) {
  49. setTimeout(arguments.callee, 0);
  50. }
  51. })();
  52.  
  53. return this;
  54. })();

Report this snippet  

You need to login to post a comment.