What is the DOMContentLoaded event and when to use it
· Category: JavaScript
Short answer
DOMContentLoaded fires when the HTML document has been fully parsed and deferred scripts have executed, without waiting for stylesheets, images, or subframes to load.
How it works
The browser parses HTML into a DOM tree. Once parsing is complete and synchronous scripts have run, DOMContentLoaded fires. This is earlier than window.onload, which waits for all dependent resources.
Example
document.addEventListener("DOMContentLoaded", () => {
const nav = document.querySelector("nav");
initNavigation(nav);
});
// Modern alternative: place script with type="module" at the end of <body>
Why it matters
Attaching handlers after DOM readiness prevents null selections and ensures elements exist. For module scripts or scripts at the end of the body, this event is usually unnecessary.
Common issues
- Scripts in the
<head>withoutdeferblock parsing and delayDOMContentLoaded. - Inline scripts that query the DOM before it is ready throw errors if the script runs in the
<head>.