Since the window.onload event needs to be executed after all the content of the page (including images, etc.) is loaded, we often prefer to execute the script as soon as the DOM is loaded. In fact, most mainstream browsers (Firefox 3+, Opera 9+, Safari 3+, Chrome 2+) provide this event method: addDOMLoadEvent.
document.addEventListener("DOMContentLoaded", init, false);
So how do we simulate the addDOMLoadEvent event for IE?
Matthias Miller first provided the following solution:
// for Internet Explorer (using conditional comments)
/*@cc_on @*/
/*@if (@_win32)
document.write("<script id=__ie_onload defer src=javascript:void(0)></script>");
var script = document.getElementById("__ie_onload");
script.onreadystatechange = function() {
if (this.readyState == "complete") {
init(); // call the onload handler
}
};
/*@end @*/
Diego Perini later provided a solution that uses the doScroll() method to simulate the addDOMLoadEvent event, and this solution is basically adopted by mainstream JavaScript frameworks (JQuery, YUI, etc.).
The principle is basically as follows:
When the ondocumentready event fires, the document (document) has been fully parsed and created. If the component needs to manipulate the original document structure, initialization code needs to be placed after this. The ondocumentready event tells the component that the entire page has been loaded and is fired immediately before the initial document's onload event fires.
Some methods, such as doScroll, require that the original document be fully loaded. If these methods are part of the initialization function, they will be executed when the ondocumentready event fires.
/*
*
*IEContentLoaded.js
*
* Author: Diego Perini (diego.perini at gmail.com) NWBOX Srl
* Summary: DOMContentLoaded emulation for IE browsers
* Updated: 05/10/2007
* License: GPL/CC
* Version: TBD
*
*/
// @w window reference
// @fn
function referencefunction IEContentLoaded (w, fn) {
var d = w.document, done = false,
// only fire once
init = function () {
if (!done) {
done = true;
fn();
}
};
// polling for no errors
(function () {
try {
// throws errors until after ondocumentready
d.documentElement.doScroll('left');
} catch (e) {
setTimeout(arguments.callee, 50);
return;
}
// no errors, fire
init();
})();
// trying to always fire before onload
d.onreadystatechange = function() {
if (d.readyState == 'complete') {
d.onreadystatechange = null;
init();
}
};
}