domcontentLoaded

This guide explores four important JavaScript events—DOMContentLoaded, load, beforeunload, and unload—that control webpage behavior at various points during user interaction and the page lifecycle.

DOMContentLoaded Event

The DOMContentLoaded event triggers once the HTML document is fully parsed and any deferred scripts have run. However, it does not wait for images, subframes, or asynchronous scripts to load. To detect when all resources, including images, are fully loaded, use the load event.

Syntax

index.html
<element DOMContentLoaded="script"></element>
There is no risk of a race condition in this scenario. The document cannot transition from loading to fully loaded between the if-check and the event listener attachment. This is because JavaScript follows run-to-completion semantics, ensuring that once the script starts executing in a given event loop cycle, no other tasks can interrupt it. If the document is still loading during that cycle, it will only reach the loaded state in the next cycle—by which time the event listener will already be set up and ready to trigger when the event occurs.

Example

The example below listens for the DOMContentLoaded event and updates a <div> element as soon as the document is parsed—before the full page load completes.

::event-loaded ::
<div class="controls">
  <button id="reload" type="button">Reload</button>
</div>

<div class="event-log">
  <label for="eventLog">Event log:</label>
  <textarea
    readonly
    class="event-log-contents"
    rows="8"
    cols="30"
    id="eventLog"></textarea>
</div>
You can add this snippet to an HTML file and open it in a browser to see how quickly DOMContentLoaded fires compared to the full page load.

Conclusion

The DOMContentLoaded event allows scripts to execute as soon as the HTML is parsed, without waiting for additional resources like images. This improves responsiveness and enhances webpage performance, making it a crucial event for optimizing user experience.