DOMContentLoaded event

document.addEventListener('DOMContentLoaded', listener)

Fires as soon as the browser parses the whole HTML and builds the element tree – it does not wait for images and styles (the load event of the window waits for those). From that moment it is safe to look for elements.

The example works with the HTML above the code; an event that a user would trigger is triggered by the code (for example click()).

Examples

<p id="status"></p>
const init = () => {
  document.getElementById('status').textContent = 'script started';
  console.log('init:', document.getElementById('status').textContent);
};
if (document.readyState === 'loading') {
  document.addEventListener('DOMContentLoaded', init);
} else {
  init();
}
console.log(document.readyState);

Output:

init: script started
complete

Things to watch out for

  • A listener added after the event is not called – code that can run late (loaded dynamically) tests document.readyState (see the example).
  • Scripts with the defer attribute or type="module" run only after the HTML is parsed, so they do not need DOMContentLoaded.

Browser support

Baseline – widely available: works in all major browsers and has for a long time (since 2015 at the latest). Since version: Chrome 1, Firefox 1, Safari 3.1; not in Node.js (a browser API). As of October 2026 (MDN browser-compat-data).

Related:
EventTarget.addEventListener()
Document.querySelector()