CKTIS / JavaScript
DOMContentLoaded, pagehide, and pageshow: DOM readiness and navigation
Tell when the DOM is ready, when navigation takes you away from a document, and when the browser restores it. Learn what `readyState` and `persisted` actually tell you.
Version: ECMAScript 2024 and the current web platform; runtime support varies
Syntax
document.addEventListener("DOMContentLoaded", onDomReady, { once: true });
window.addEventListener("pagehide", onPageHide);
window.addEventListener("pageshow", onPageShow);
// onPageHide and onPageShow receive a PageTransitionEvent with a boolean persisted property.The DOMContentLoaded/pagehide/pageshow events distinguish DOM readiness from navigation. Listen for DOMContentLoaded, a browser Event, on document. It fires after HTML parsing finishes and deferred classic scripts have run. Before firing it, the browser also initiates evaluation of parser-inserted module scripts without async. It does not wait for top-level await in those modules or their dependencies, so module initialization can still be pending after the event fires. It doesn't wait for images, frames, or async scripts; stylesheets can delay it indirectly by blocking deferred scripts. It isn't the load event.
If your code may run late and only needs the parsed DOM, check document.readyState. If it's "loading", add a one-time DOMContentLoaded listener; otherwise, initialize immediately. "interactive" means parsing has finished, not that DOMContentLoaded has fired or that other scripts have finished setting up.
On window, listen for pagehide when leaving a document and pageshow when it loads or is restored. Both are PageTransitionEvent events with a boolean persisted. On pagehide, true means the document may be reused, not that it definitely will be; false means it won't be reused. On a fresh load, pageshow follows load with false. On a back/forward cache (bfcache) restore, it has true: the same DOM and JavaScript state return without another DOMContentLoaded.
Use pagehide to pause page-specific work and pageshow with persisted === true to resume it or refresh stale data. pagehide may not fire, for example if a mobile browser is killed in the background. Save important changes as they happen; use visibilitychange and document.visibilityState for visibility changes. These events aren't signals for ordinary tab switches and belong to the web platform, not ECMAScript.
Examples
(() => {
function installListeners(doc, win) {
const onDomReady = () => console.log("DOM ready");
if (doc.readyState === "loading") {
doc.addEventListener("DOMContentLoaded", onDomReady, { once: true });
} else {
onDomReady();
}
const logTransition = (event) => {
console.log(`${event.type} persisted=${event.persisted}`);
};
win.addEventListener("pagehide", logTransition);
win.addEventListener("pageshow", logTransition);
}
if (typeof document !== "undefined" && typeof window !== "undefined") {
installListeners(document, window);
} else {
// Node.js test: simulate DOM readiness without simulating navigation.
const testDocument = new EventTarget();
const testWindow = new EventTarget();
testDocument.readyState = "loading";
installListeners(testDocument, testWindow);
testDocument.readyState = "interactive";
testDocument.dispatchEvent(new Event("DOMContentLoaded"));
}
})();Result
DOM ready
Paste the code once into the browser console after the page has fully loaded. `DOM ready` then comes from the `readyState` check, not from a replayed event. Preserve the console log, navigate to another document in the same tab, and go Back. Extra lines depend on navigation and whether the browser uses the bfcache.
Related lessons
- JavaScript · Lesson 37 · Advanced · Version: 4