For more tips like this, sign up to the weekly newsletter!
Use DOMContentLoaded
to wait for page ready
To wait for the DOM to load and start interacting with it (render React, for example), use the DOMContentLoaded
event of the document
.
document.addEventListener("DOMContentLoaded", () => {
// The DOM is ready
});
This construct supports multiple listeners to the same event; they won't interfere. And fortunately, all browsers support it.
Legacy ways
The old way is to set the onload
handler in window
:
window.onload = () => {
// The page is loaded
}
There is a difference when they run, as the onload
waits for all the assets to load, while the DOMContentLoaded
is fired as soon as the DOM is ready. But for initializations of frameworks, the latter is enough.
Also, this construct does not support multiple handlers:
window.onload = () => {
// Doesn't run
}
window.onload = () => {
}
To remedy this, manually call the previous handler:
window.onload = ((prev) => (...args) => {
prev && prev(...args);
// Do the initializations ...
})(window.onload)
Better still, use the addEventListener
to attach the handlers, which does not suffer from the multiple-listeners problem:
window.addEventListener("load", () => {
// Do the initializations ...
})