Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

DOMContentLoaded and the once listener option

Use `DOMContentLoaded` to wait for HTML parsing and `{ once: true }` to limit a listener registration to one call. Check `document.readyState` when your setup code can run late.

Version: HTML Living Standard and DOM Standard; runtime support varies

Syntax

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

// Instead, if init only needs the parsed DOM and may be set up late:
if (document.readyState === "loading") {
  document.addEventListener("DOMContentLoaded", init, { once: true });
} else {
  init();
}

The browser fires DOMContentLoaded on document after parsing the HTML and running the scripts scheduled for after parsing: defer scripts and non-async modules. It does not wait for work that resumes after a top-level await. Unlike load, it does not wait for images, subframes, or async scripts. Stylesheets can delay it indirectly if they block scripts that the event waits for.

In document.addEventListener("DOMContentLoaded", init, { once: true }), the once option removes that registration automatically before the event first calls init. It defaults to false. A bare true as the third argument sets capture, not once. The option neither replays a past event nor limits manual calls or later registrations.

If init only needs the parsed DOM, check document.readyState: when it is "loading", register the listener; otherwise call init() immediately. The browser event cannot fire between this synchronous check and registration. "interactive" means parsing is finished, not that DOMContentLoaded has already fired. If setup depends on another script, coordinate with that script explicitly.

The event, readiness property, and listener option are web platform APIs, not ECMAScript features. ECMAScript 2024 support does not guarantee their availability in a given runtime.

Examples

(() => {
  const target = new EventTarget();
  let calls = 0;

  target.addEventListener("DOMContentLoaded", () => {
    calls += 1;
  }, { once: true });

  target.dispatchEvent(new Event("DOMContentLoaded"));
  console.log(`After first dispatch: ${calls}`);

  target.dispatchEvent(new Event("DOMContentLoaded"));
  console.log(`After second dispatch: ${calls}`);
})();

Result

After first dispatch: 1
After second dispatch: 1

Run this in a browser console. Two synthetic events with the same name are dispatched on a separate `EventTarget`, not on `document`. They demonstrate `once`, not when the page becomes ready.

Related lessons

  • JavaScript · Lesson 39 · Intermediate · Version: 3

Sources