I know there are some ways to get notified when the page body has loaded (before all the images and 3rd party resources load which fires the window.onload e
The fancy crossbrowser solution you are looking for....doesn't exist... (imagine the sound of a big crowd saying 'aahhhh....').
DomContentLoaded is simply your best shot. You still need the polling
technique for IE-oldies.
I've found the following code sample on javascript.info which you can use to cover all browsers:
function bindReady(handler){
var called = false
function ready() {
if (called) return
called = true
handler()
}
if ( document.addEventListener ) { // native event
document.addEventListener( "DOMContentLoaded", ready, false )
} else if ( document.attachEvent ) { // IE
try {
var isFrame = window.frameElement != null
} catch(e) {}
// IE, the document is not inside a frame
if ( document.documentElement.doScroll && !isFrame ) {
function tryScroll(){
if (called) return
try {
document.documentElement.doScroll("left")
ready()
} catch(e) {
setTimeout(tryScroll, 10)
}
}
tryScroll()
}
// IE, the document is inside a frame
document.attachEvent("onreadystatechange", function(){
if ( document.readyState === "complete" ) {
ready()
}
})
}
// Old browsers
if (window.addEventListener)
window.addEventListener('load', ready, false)
else if (window.attachEvent)
window.attachEvent('onload', ready)
else {
var fn = window.onload // very old browser, copy old onload
window.onload = function() { // replace by new onload and call the old one
fn && fn()
ready()
}
}
}
Using a library like jQuery will save you countless hours of browsers inconsistencies.
In this case with jQuery you can just
$(document).ready ( function () {
//your code here
});
If you are curious you can take a look at the source to see how it is done, but is this day and age I don't think anyone should be reinventing this wheel when the library writer have done all the painful work for you.
There's no cross-browser method for checking when the DOM is ready -- this is why libraries like jQuery exist, to abstract away nasty little bits of incompatibility.
Mozilla, Opera, and modern WebKit support the DOMContentLoaded
event. IE and Safari need weird hacks like scrolling the window or checking stylesheets. The gory details are contained in jQuery's bindReady()
function.