Page DOM and Browser loading
suggest changeThis is an example to explain the variations of load events.
- onload event
<body onload="someFunction()">
<img src="image1" />
<img src="image2" />
</body>
<script>
function someFunction() {
console.log("Hi! I am loaded");
}
</script>
In this case, the message is logged once all the contents of the page, including the images and stylesheets (if any), are completely loaded.
- DOMContentLoaded event
document.addEventListener("DOMContentLoaded", function(event) {
console.log("Hello! I am loaded");
});
In the above code, the message is logged when the document has been parsed. It does not wait for images. Stylesheets can still delay it when a script follows them.
- Immediately invoked function expression
(function(){
console.log("Hi I am an anonymous function! I am loaded");
})();
The function runs when that script is evaluated. If the script appears before the rest of the document, this can happen before the DOM is complete.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents