Window and Document Events: load, DOMContentLoaded, resize
You'll learn the critical timing differences between page load events and how to respond to window size changes.
Understanding Event Timing
When a web page loads, multiple events fire at different stages. Knowing which event to use is crucial for performance and correct behavior.
DOMContentLoaded fires when the HTML document has been completely parsed and the DOM tree is built, but before images, stylesheets, and other external resources finish loading. Think of it like the frame of a house being complete—you can walk through and interact with the structure, even though the paint and furniture aren't done yet.
load fires only after everything has finished loading—images, stylesheets, fonts, and all other resources. This is like waiting until the house is completely furnished and decorated before moving in.
When to Use Which
Use DOMContentLoaded when you need to manipulate the DOM or attach event listeners. Your JavaScript can run sooner, making your page feel faster:
document.addEventListener('DOMContentLoaded', () => {
const button = document.querySelector('button');
button.addEventListener('click', handleClick);
});
Use load only when you truly need to wait for images or other resources:
window.addEventListener('load', () => {
console.log('All images and resources loaded');
});
Handling Window Resize
The resize event fires whenever the browser window changes size. Be cautious—it can fire rapidly during resizing:
window.addEventListener('resize', () => {
console.log('Window resized to:', window.innerWidth, window.innerHeight);
});
Key Takeaway: Use DOMContentLoaded for DOM manipulation (fires early), load when you need all resources loaded, and resize to respond to window size changes—but be mindful of performance with frequently-firing events.