How to detect document.ready in JavaScript?

Possible Duplicate:
$(document).ready equivalent without jQuery

I have a framework-less javascript that executes on load:

function myJs() {    
   // some code
}
window.load = myJs;

But this causes a delay in the execution of the script. I want to be able to execute this script as soon as the document is ready to be manipulated even before the page has completely finished loading. How can this be done in a cross browser compatible way? In other words how can the:

$(document).ready(function() {  
   //
});

of jQuery be said in plain JS?


我已经做了一个实现(基于jQuery中的实现),您可以使用它:http://github.com/jakobmattsson/onDomReady/blob/master/ondomready.js


//old IE
document.onreadystatechange = function() {
   if (this.readyState === "complete"){
      //whatev
   }
};


//for everyone else
document.addEventListener("DOMContentLoaded", function () {
  //whatev
  }, false);

It's actually not that bad. You need a way to add events to document , and the knowledge of what those events should be. Using the standard addEvent function

function addEvent( obj, type, fn )
{
 if (obj.addEventListener)
 {
   obj.addEventListener( type, fn, false );
 }
 else if (obj.attachEvent)
 {
  obj["e"+type+fn] = fn;
  obj[type+fn] = function() { return obj["e"+type+fn]( window.event ); };
  obj.attachEvent( "on"+type, obj[type+fn] );
 }
}

You can do the following:

// IE
addEvent(document, 'DOMContentLoaded', function() {
    alert('ready');
});

// Other
addEvent(document, 'onreadystatechange', function() {
    if (document.readyState == 'complete')
        alert('ready');
});

// For demonstration purposes, show a 'load' event
addEvent(window, 'load', function() {
    alert('load');
});

The IE event handler will simply not fire in other browsers, and vice-versa.

链接地址: http://www.djcxy.com/p/71246.html

上一篇: 在Javascript中使用jquery文档准备好了吗?

下一篇: 如何在JavaScript中检测document.ready?