Episode 42 of 46
The Window Onload Event
Learn how to run JavaScript after the page has fully loaded.
The load event fires when the entire page (HTML, CSS, images, scripts) has finished loading. This ensures your JavaScript runs after everything is ready.
window.onload
window.onload = function() {
console.log("Page fully loaded!");
// Safe to manipulate DOM here
let title = document.querySelector("h1");
title.textContent = "Page Ready!";
};
DOMContentLoaded (Recommended)
DOMContentLoaded fires when the HTML is parsed — before images and stylesheets finish loading. It's faster:
document.addEventListener("DOMContentLoaded", function() {
console.log("DOM is ready!");
// DOM elements are available, but images may still be loading
});
load vs DOMContentLoaded
DOMContentLoaded— fires when HTML is parsed (faster)load— fires when everything is loaded (images, CSS, etc.)
document.addEventListener("DOMContentLoaded", function() {
console.log("1. DOM ready");
});
window.addEventListener("load", function() {
console.log("2. Everything loaded");
});
// Output order: 1 first, then 2
Why Not Just Use defer?
<!-- This script runs after HTML is parsed -->
<script src="app.js" defer></script>
Using defer on your script tag achieves the same effect as DOMContentLoaded — and is often simpler.
Other Window Events
// Before the user leaves the page
window.addEventListener("beforeunload", function(e) {
e.preventDefault();
e.returnValue = ""; // Shows "Are you sure?" dialog
});
// Window resize
window.addEventListener("resize", function() {
console.log("Width:", window.innerWidth);
console.log("Height:", window.innerHeight);
});