CKTIS / JavaScript
DOMContentLoaded, pagehide, and scroll events
Distinguish DOM readiness, page departure, and scrolling. Attach each listener to the right object and account for restoration from the back/forward cache.
Version: ECMAScript 2024 and the current web platform; runtime support varies
Syntax
document.addEventListener("DOMContentLoaded", onReady, { once: true });
window.addEventListener("pagehide", onPageHide);
document.addEventListener("scroll", onDocumentScroll);
scrollBox.addEventListener("scroll", onElementScroll);The DOMContentLoaded/pagehide/scroll events answer three different questions: Is the DOM ready for setup? Is the browser leaving this document? Has the scroll position changed? These are web platform events, not ECMAScript features; do not assume a non-browser runtime provides document and window.
DOMContentLoaded fires on document after HTML parsing completes, deferred classic scripts have run, and the browser has initiated evaluation of the non-async module scripts scheduled for the end of parsing. It does not wait for asynchronous module evaluation to finish: a top-level await in a dependency can delay execution of the importing module’s body until after the event. Unlike load, it does not wait for images, subframes, or async scripts. A stylesheet can still delay it indirectly by blocking a script.
If setup code might run late, check document.readyState. While it is "loading", register a one-time DOMContentLoaded listener; otherwise, initialize immediately. "interactive" means parsing is complete, not that the event has already fired or that other deferred scripts have finished.
Listen for pagehide on window when you need to react to the browser leaving the document, not merely switching tabs. On that PageTransitionEvent, event.persisted === true signals possible reuse from the back/forward cache (bfcache), not a guarantee of restoration; false means this document is not being kept for reuse. To resume on restoration, use pageshow with persisted === true, not DOMContentLoaded. pagehide can be missed, for example if the OS terminates a mobile browser. Save important state as you go; to detect a tab becoming hidden, use visibilitychange and check for "hidden".
Listen for scroll on document for page scrolling and read window.scrollY; for a scrolling container, listen on the element itself and read its scrollTop. Code-driven scrolling can also fire the event, which does not indicate that scrolling has stopped. Keep the handler cheap because events can arrive rapidly; throttle expensive updates if needed.
Examples
(() => {
const viewportHeight = 80;
const contentHeight = 240;
function run(page, doc, createScrollBox) {
page.addEventListener("pagehide", (event) => {
console.log(`pagehide: persisted=${event.persisted}`);
});
function init() {
console.log("DOM ready");
const box = createScrollBox();
box.addEventListener("scroll", () => {
console.log(`scroll: ${box.scrollTop}`);
}, { once: true });
box.scrollTop = 40;
}
if (doc.readyState === "loading") {
doc.addEventListener("DOMContentLoaded", init, { once: true });
} else {
init();
}
}
if (typeof window !== "undefined" && typeof document !== "undefined") {
run(window, document, () => {
const box = document.createElement("div");
box.style.cssText = `width: 200px; height: ${viewportHeight}px; overflow: auto`;
const content = document.createElement("div");
content.style.height = `${contentHeight}px`;
content.textContent = "Scroll demo";
box.append(content);
document.body.append(box);
return box;
});
return;
}
// Node.js stand-ins exercise the same listeners without a browser DOM.
class ScrollBox extends EventTarget {
#offset = 0;
get scrollTop() {
return this.#offset;
}
set scrollTop(value) {
const offset = Math.min(Math.max(0, value), contentHeight - viewportHeight);
if (offset === this.#offset) return;
this.#offset = offset;
setTimeout(() => this.dispatchEvent(new Event("scroll")), 0);
}
}
const page = new EventTarget();
const doc = new EventTarget();
doc.readyState = "loading";
run(page, doc, () => new ScrollBox());
doc.readyState = "interactive";
doc.dispatchEvent(new Event("DOMContentLoaded"));
})();Result
DOM ready scroll: 40
Run once in the console of a loaded blank HTML page. Setup runs immediately, and the code scrolls the container for you. Enable Preserve log and navigate to another document in the same tab to look for an additional `pagehide: persisted=true` or `pagehide: persisted=false` line. That line is not guaranteed. In Node.js, `EventTarget` stand-ins exercise the same readiness and scroll handlers without testing actual browser behavior.
Related lessons
- JavaScript · Lesson 45 · Advanced · Version: 4