What the jQuery is to read the property document.readyState
when the page loads, and if it is not already loaded, listen to one of the events load
or DOMContentLoad
. The first event to be called triggers the ready
.
In practice simplifying would be so (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 scroll and so this line that refers to Scroll. There’s a very good article about that (link), but since IE8 is no longer supported you can remove.
To version of Mootools is similar, a little more complex and therefore more complete, and uses the internal mechanism of Mootools events. Also take into account older browsers that do not have readystatechange
. But that no longer matters in today’s times.
For modern browsers this can be done (link):
var domReady = function(ready) {
if (document.readyState != 'loading') return ready();
document.addEventListener('DOMContentLoaded', ready);
function _ready() {
document.removeEventListener('DOMContentLoaded', ready);
ready();
}
}
For old browsers this could be done (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);
}
}
Look at this other topic Pure Javascript equivalent to jQuery’s $.ready() how to call a Function when the page/dom is ready for it.
– William Novak
There is a specific website on this subject: Youmightnotneedjquery.
– Renan Gomes
Liked @Renan :D
– Wallace Maxters