JavaScript: DOMContentLoaded
The DOMContentLoaded event fires after the HTML has been parsed and the DOM is ready to inspect or update.
What you will learn
- When DOMContentLoaded runs
- How it differs from the window load event
- When a script can skip the listener safely
Minimal example
document.addEventListener('DOMContentLoaded', () => {
const title = document.querySelector('h1');
if (title) title.classList.add('ready');
});Use the event when the script may run before the elements it needs exist. A defer script runs after parsing, so it often can initialize directly without waiting for another event.
Common mistakes
- Do not wait for
loadwhen only the DOM is needed; load also waits for images and other resources. - Do not register initialization twice, or controls may receive duplicate listeners.
- Account for scripts loaded dynamically after the event has already fired.