Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

DOMContentLoaded — DOM tree readiness

DOMContentLoaded signals that HTML parsing and deferred script execution have finished. Use it to initialize an interface without waiting for the entire page to load.

Version: ECMAScript and Web APIs; exact feature edition and browser support reviewed per entry; Node 24 in repository does not prove browser API support

Syntax

document.addEventListener("DOMContentLoaded", init, { once: true });

DOMContentLoaded is an event fired at document after HTML parsing and deferred script execution finish. It belongs to the HTML standard, not ECMAScript; current browser engines support it. Having Node 24 alone does not provide the browser's document.

It does not mean all resources have loaded: it does not wait for images or async scripts. The later load event on window represents a fuller loading milestone. Stylesheets can indirectly delay DOMContentLoaded by blocking deferred script execution.

A listener added after the event does not run retroactively. The example therefore checks document.readyState: when it is "loading", it registers init; otherwise, it calls it immediately. The "interactive" state means parsing has finished, but does not prove that DOMContentLoaded has already fired. This pattern handles DOM readiness; it does not guarantee waiting for remaining deferred scripts.

The example's script precedes the paragraph. Waiting prevents looking up the element too early; after initialization, both the paragraph and console show DOM ready.

Examples

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>DOMContentLoaded example</title>
  <script>
    function init() {
      document.getElementById("status").textContent = "DOM ready";
      console.log("DOM ready");
    }

    if (document.readyState === "loading") {
      document.addEventListener("DOMContentLoaded", init, { once: true });
    } else {
      init();
    }
  </script>
</head>
<body>
  <p id="status">Waiting</p>
</body>
</html>

Result

DOM ready

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources