One of the most commonly used events is waiting for the document to have loaded, including both script files and images. The load
event on document
is used for this.
document.addEventListener('load', function() {
console.log("Everything has now loaded!");
});
Sometimes you try to access a DOM object before it is loaded, causing null pointers. These are really tough to debug. To avoid this use document
's DOMContentLoaded
event instead. DOMContentLoaded
ensures that the HTML content has been loaded and initialized without waiting for other external resources.
document.addEventListener('DOMContentLoaded', function() {
console.log("The document contents are now available!");
});