Searching for the perfect crossbrowser solution? Unfortunately, it seems like such a thing doesn't actually exist... (cue the collective disappointed sigh).
If you're aiming for the best option, DomContentLoaded is your go-to choice. However, for those using older versions of IE, incorporating the polling
technique is necessary.
- First attempt to utilize addEventListener;
- If that's not an option (looking at you, IE), investigate frames;
- In case there's no frame, continuously scroll until errors cease (polling);
- If dealing with a frame, employ the IE event document.onreadystatechange;
- Lastly, for browsers lacking support, revert to the traditional document.onload event.
Fortunately, I stumbled upon this code snippet on javascript.info, providing a comprehensive solution for 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) {}
// Handling when the document is not in a frame
if ( document.documentElement.doScroll && !isFrame ) {
function tryScroll(){
if (called) return
try {
document.documentElement.doScroll("left")
ready()
} catch(e) {
setTimeout(tryScroll, 10)
}
}
tryScroll()
}
// Handling when the document is in a frame
document.attachEvent("onreadystatechange", function(){
if ( document.readyState === "complete" ) {
ready()
}
})
}
// For 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 with new onload and execute the old one
fn && fn()
ready()
}
}
}