DOMContentLoaded vs Load Events
You'll learn: The crucial difference between when your HTML structure is ready versus when everything on your page has finished downloading.
The Two Key Browser Events
When a browser loads your web page, it fires two important events at different times, and understanding the difference is critical for performance optimization and proper script execution.
DOMContentLoaded: HTML is Parsed
The DOMContentLoaded event fires as soon as the browser has completely parsed the HTML document and built the DOM tree. At this point:
- All HTML elements are accessible via JavaScript
- The DOM structure is fully constructed
- CSS may still be loading
- Images, videos, and other external resources are not necessarily loaded yet
Think of it like a house where the walls and rooms are built, but the furniture and decorations haven't all arrived yet. You can walk through and see the structure, but it's not completely furnished.
document.addEventListener('DOMContentLoaded', () => {
console.log('DOM is ready!');
// Safe to manipulate elements now
document.querySelector('h1').textContent = 'Updated!';
});
Load: Everything is Downloaded
The load event fires only after the HTML and all dependent resources have finished loading—images, stylesheets, scripts, iframes, everything.
window.addEventListener('load', () => {
console.log('Page fully loaded!');
// All images and resources are now available
});
This is like waiting until every piece of furniture is delivered and every picture is hung. The house is completely ready.
Why It Matters for Performance
DOMContentLoaded happens much faster and is often the better choice for initializing interactive features. Users can start engaging with your page sooner. The load event is better when you specifically need images or other resources to be ready.
Key Takeaway: DOMContentLoaded fires when HTML is parsed (DOM ready), while load fires when all resources finish downloading—choose based on what your code actually needs.