Edit: As the year 2018 comes upon us, I think it's safe to listen for the DOMContentLoaded
event.
function fireOnReady() { /* ... */ }
if (document.readyState === 'complete') {
fireOnReady();
} else {
document.addEventListener("DOMContentLoaded", fireOnReady);
}
Please note, the event will only fire once when your page loads! If you have to support really old browsers, then check out the super lightweight script I put together below.
For historical reference only:
jQuery has an undocumented property called isReady which is used internally to determine whether the DOM ready event has fired:
if($.isReady) {
// DOM is ready
} else {
// DOM is not yet ready
}
I started at 1.5.2 went back as far as 1.3.2 and the property is there. While undocumented, I would say that you can rely on this property in future versions of jQuery.
Edit: And a year later - v1.7.2, they still use $.isReady
- still undocumented, so please use at your own risk. Be careful when upgrading.
Edit: v1.9, they still use $.isReady
- still undocumented
Edit: v2.0, with all of it's "major" changes, still uses $.isReady
- still undocumented
Edit: v3.x still uses $.isReady
- still undocumented
Edit: As several people have pointed out, the above does not really answer the question. So I have just created a mini DOM ready snippet which was inspired by Dustin Diaz's even smaller DOM ready snippet. Dustin created a neat way to check the document readyState with something similar to this:
if( !/in/.test(document.readyState) ) {
// document is ready
} else {
// document is NOT ready
}
The reason this works is because the browser has 3 loading states: "loading", "interactive", and "complete" (older WebKit also used "loaded", but you don't have to worry about that any more). You will notice that both "loading" and "interactive" contain the text "in"... so if the string "in" is found inside of document.readyState
, then we know we are not ready yet.
document.addEventListener('DOMContentLoaded' ...
, as suggested below (almost hidden), instead of a library. – Testicle