Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

DOMContentLoaded, pagehide, and resize events

Choose the event that matches the job: `DOMContentLoaded` for DOM readiness, `pagehide` for leaving a page, and `resize` for viewport size changes.

Version: ECMAScript 2024 and the current web platform; runtime support varies

Syntax

document.addEventListener("DOMContentLoaded", onDomReady, { once: true });
window.addEventListener("pagehide", onPageHide);
window.addEventListener("resize", onResize);

The DOMContentLoaded/pagehide/resize events belong to the web platform, not ECMAScript 2024. Register them with addEventListener(): use document for the first and window for the other two. Availability depends on the runtime; do not assume that a worker or Node.js provides these browser event targets.

DOMContentLoaded is a non-cancelable Event that bubbles from document. The browser fires it after parsing the HTML, running classic scripts with defer, and initiating evaluation of module scripts scheduled for after parsing (those without async). It does not wait for asynchronous module evaluation to finish: a module can still be suspended at a top-level await, or its body may not have started because it is still waiting for an asynchronous dependency. Unlike load, it does not directly wait for images, frames, or async scripts. If you only need the parsed DOM, listen with { once: true } when document.readyState === "loading"; otherwise initialize immediately. "interactive" does not prove the event has fired or that deferred scripts have set up state your code depends on.

pagehide is a PageTransitionEvent listened for on window when leaving a page, not merely switching tabs. event.persisted === true means the page may be kept in the back/forward cache (bfcache); false means that document will not be restored that way. true does not guarantee a return: detect actual restoration with pageshow and persisted === true, without a new DOMContentLoaded. preventDefault() does not block navigation. pagehide can be missed, especially on mobile, so save important data earlier; to detect backgrounding, use visibilitychange and check document.visibilityState === "hidden".

The window resize is a non-cancelable Event that does not bubble. It reports viewport size changes, not changes to arbitrary elements. Read the current dimensions from window.innerWidth and window.innerHeight, and use ResizeObserver to watch an element's size. Changes can come in quick succession, so limit how often you do expensive layout work.

Examples

(() => {
  const documentTarget = globalThis.document ?? new EventTarget();
  const windowTarget = globalThis.window ?? new EventTarget();
  const controller = new AbortController();
  const options = { signal: controller.signal };

  documentTarget.addEventListener("DOMContentLoaded", (event) => {
    console.log(event.type);
  }, options);
  windowTarget.addEventListener("pagehide", (event) => {
    console.log(`${event.type}: persisted=${event.persisted}`);
  }, options);
  windowTarget.addEventListener("resize", (event) => {
    console.log(event.type);
  }, options);

  try {
    documentTarget.dispatchEvent(new Event("DOMContentLoaded", { bubbles: true }));
    const pagehide = typeof PageTransitionEvent === "function"
      ? new PageTransitionEvent("pagehide", { persisted: true })
      : Object.assign(new Event("pagehide"), { persisted: true });
    windowTarget.dispatchEvent(pagehide);
    windowTarget.dispatchEvent(new Event("resize"));
  } finally {
    controller.abort();
  }
})();

Result

DOMContentLoaded
pagehide: persisted=true
resize

Run in the browser console on a fresh `about:blank` tab, or save the snippet as `main.js` and run `node main.js` with Node.js 24. In Node.js, the example uses standalone `EventTarget` instances instead of `document` and `window`. Synthetic events check listener wiring; they do not change document readiness or viewport size, navigate, or exercise the bfcache. `abort()` removes all three listeners.

Related lessons

  • JavaScript · Lesson 34 · Advanced · Version: 4

Sources