Page Load Events
Page lifecycle events tell your code where the page is in its life: the HTML has been parsed, every image has loaded, the person switched to another tab, the page is about to close. Running code at the wrong moment causes classic bugs: a script that can't find elements because they don't exist yet, or unsaved data lost when someone closes the tab. This lesson covers the events and script attributes that put your code at the right moment.
In One Minute
DOMContentLoaded: the HTML is parsed and the DOM is ready (images may still be loading).load(onwindow): everything, including images, stylesheets and iframes, has loaded.- Scripts with
deferortype="module"run just beforeDOMContentLoaded, so they rarely need either event. visibilitychangereports when the tab is hidden or shown: save state and pause work there.pagehidefires when the page is going away;beforeunloadcan ask "Leave site?" when there are unsaved changes.
The Loading Sequence
| Step | document.readyState | Event |
|---|---|---|
| HTML is being parsed | "loading" | |
Parsing finished; defer and module scripts run | "interactive" | DOMContentLoaded on document |
| Images, stylesheets, iframes finished | "complete" | load on window |
<p id="msg">Hello</p>
<img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" alt="">
<script>
console.log("script runs, readyState:", document.readyState);
document.addEventListener("DOMContentLoaded", () => console.log("DOMContentLoaded, readyState:", document.readyState));
window.addEventListener("load", () => console.log("load, readyState:", document.readyState));
</script>script runs, readyState: loading
DOMContentLoaded, readyState: interactive
load, readyState: completeExplanation: the inline script runs while the page is still being parsed. DOMContentLoaded fires once the whole HTML is parsed, and load fires after the image (and anything else) has loaded too. On a real page with large images, the gap between the last two can be seconds.
DOMContentLoaded
Use DOMContentLoaded when a classic script in the <head> (without defer) needs the page's elements:
<!doctype html>
<html>
<head>
<script>
console.log("in head:", document.querySelector("#total"));
document.addEventListener("DOMContentLoaded", () => {
console.log("after parse:", document.querySelector("#total").textContent);
});
</script>
</head>
<body><p id="total">$530</p></body>
</html>in head: null
after parse: $530In the <head>, the paragraph doesn't exist yet, so querySelector returns null. Inside the DOMContentLoaded listener, it does.
defer and Modules Make It Simpler
A script with defer, or any module script, downloads in parallel with parsing and runs after the HTML is parsed (but before DOMContentLoaded). Their code can use the DOM directly, without any event:
<head>
<script src="app.js" defer></script>
<!-- or -->
<script type="module" src="app.js"></script>
</head>| Script | Runs | Needs DOMContentLoaded? |
|---|---|---|
<script> at the end of <body> | When reached, DOM above it is ready | No |
<script> in <head> | Immediately, before the body exists | Yes |
<script defer> | After parsing, in order | No |
<script type="module"> | After parsing, in order (deferred by default) | No |
<script async> | As soon as it downloads, any order | Maybe (use for independent scripts only) |
When the Event Has Already Fired
Code loaded late (for example, by import() after the page is ready) can miss DOMContentLoaded. Check readyState first:
function whenReady(fn) {
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", fn, { once: true });
} else {
fn();
}
}load
The load event on window waits for everything, including images. Use it only when you need loaded resources, such as measuring an image's size. Individual images and scripts also fire their own load and error events:
<img id="logo" alt="Logo">
<img id="broken" alt="Missing">
<script>
const logo = document.querySelector("#logo");
logo.addEventListener("load", () => console.log("logo loaded:", logo.naturalWidth, "x", logo.naturalHeight));
logo.src = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7";
const broken = document.querySelector("#broken");
broken.addEventListener("error", () => console.log("image failed to load"));
broken.src = "data:image/png;base64,bm90LWFuLWltYWdl";
</script>logo loaded: 1 x 1
image failed to loadAttach load and error listeners before setting src, so a cached image that loads instantly can't fire before you're listening.
visibilitychange: Tab Hidden or Shown
When someone switches tabs, minimizes the window or locks their phone, the page becomes hidden. visibilitychange fires on document, and document.visibilityState is "hidden" or "visible":
document.addEventListener("visibilitychange", () => {
if (document.visibilityState === "hidden") {
saveDraft(); // the user may never come back: save now
pauseAutoRefresh();
} else {
resumeAutoRefresh();
}
});This is the most reliable moment to save state, especially on phones, where the system may close a background tab without any further events. Browsers also slow down timers in hidden tabs, so animations and polling should pause.
pagehide and beforeunload
| Event | Fires | Use for |
|---|---|---|
pagehide | The page is being left (navigation, closing); may be kept in the back/forward cache | Final cleanup; event.persisted is true if it may come back |
pageshow | The page is shown, including when restored from the back/forward cache | Refreshing data after "Back" |
beforeunload | Before leaving, while it can still be canceled | Warning about unsaved changes |
let unsaved = false;
form.addEventListener("input", () => { unsaved = true; });
form.addEventListener("submit", () => { unsaved = false; });
window.addEventListener("beforeunload", (event) => {
if (!unsaved) return;
event.preventDefault(); // the browser shows its own "Leave site?" dialog
});Browsers show a generic message; custom text is no longer displayed. Add the beforeunload listener only while there are unsaved changes: having one prevents the page from entering the back/forward cache, which makes "Back" slower.
These page-leaving events can't be meaningfully demonstrated in the checker (the page would have to close), so the examples above are shown without output.
In Practice
The Fee Tracker's startup and shutdown in one script. It's a module, so the DOM is ready when it runs; it restores a draft from storage, saves the draft whenever the tab is hidden, and warns only when there are unsaved changes:
<textarea id="note"></textarea>
<p id="state"></p>
<script type="module">
const note = document.querySelector("#note");
const state = document.querySelector("#state");
let unsaved = false;
note.value = sessionStorage.getItem("draft") ?? "";
state.textContent = note.value ? "Draft restored" : "New note";
console.log(state.textContent, "| readyState:", document.readyState);
const save = () => {
sessionStorage.setItem("draft", note.value);
unsaved = false;
};
note.addEventListener("input", () => { unsaved = true; console.log("unsaved:", unsaved); }, { once: true });
document.addEventListener("visibilitychange", () => { if (document.visibilityState === "hidden") save(); });
window.addEventListener("beforeunload", (e) => { if (unsaved) e.preventDefault(); });
</script>New note | readyState: interactive
unsaved: trueStorage (sessionStorage) has its own lesson in the next chapter.
Common Mistakes
Classic scripts in <head> that use the DOM immediately. querySelector returns null. Use defer or a module.
Waiting for load when DOMContentLoaded (or defer) is enough. load waits for every image, which can delay interactivity for seconds.
Saving data in unload or beforeunload. Unreliable. Save on visibilitychange to "hidden".
Adding beforeunload permanently. It disables the back/forward cache. Add it only while there are unsaved changes.
Practice
Challenge: Write whenReady(fn) so fn runs once the DOM is ready, whether or not DOMContentLoaded has already fired, and show it working both ways.
Show solution
<p id="x">ready</p>
<script>
function whenReady(fn) {
if (document.readyState === "loading") document.addEventListener("DOMContentLoaded", fn, { once: true });
else fn();
}
whenReady(() => console.log("first:", document.querySelector("#x").textContent));
window.addEventListener("load", () => whenReady(() => console.log("second: ran immediately")));
</script>first: ready
second: ran immediatelyKey Takeaways
| Moment | Use |
|---|---|
| DOM ready | defer / module, or DOMContentLoaded |
| Everything loaded | window load |
| Image loaded or failed | img load / error |
| Tab hidden | visibilitychange |
| Unsaved changes warning | beforeunload with preventDefault() |
Was this tutorial helpful?