What the jQuery does is to read the document.readyState
property when the page loads, and if it is not already loaded listen for one of the load
or DOMContentLoad
events. The first event to be called triggers ready
.
In practice simplifying would be like this ( jsFiddle ):
function ready() {
// quando esta função correr o DOM está acessível
}
function completed() {
document.removeEventListener("DOMContentLoaded", completed);
window.removeEventListener("load", completed);
ready();
}
if (document.readyState === "complete" ||
(document.readyState !== "loading" && !document.documentElement.doScroll)) {
ready(); // está pronto!
} else { // ainda não está pronto...
document.addEventListener("DOMContentLoaded", completed);
window.addEventListener("load", completed);
}
IE 8 had a bug with the scroll and so this line refers to Scroll. There is a very good article about it ( link ), but since IE8 is no longer supported it can be removed.
The MooTools version is similar, a bit more complex and therefore more complete, and uses MooTools' internal event engine. It also takes into account older browsers that do not have readystatechange
. But that does not matter anymore today.
For modern browsers can be done like this: link ):
var domReady = function(ready) {
if (document.readyState != 'loading') return ready();
document.addEventListener('DOMContentLoaded', ready);
function _ready() {
document.removeEventListener('DOMContentLoaded', ready);
ready();
}
}
For older browsers you could do this ( link ), keeping it simple:
var domReady = function(ready) {
var attacher = document.addEventListener ? {
add: 'addEventListener',
remove: 'removeEventListener'
} : {
add: 'attachEvent',
remove: 'detachEvent'
};
function completed() {
document[attacher.remove]("DOMContentLoaded", completed);
window[attacher.remove]("load", completed);
ready();
}
if (document.readyState === "complete" ||
(document.readyState !== "loading" && !document.documentElement.doScroll)) {
ready(); // está pronto!
} else { // ainda não está pronto...
document[attacher.add]("DOMContentLoaded", completed);
window[attacher.add]("load", completed);
}
}