Page Load Events

Updated · 7 min read
mediumES2026javascripteventsdomcontentloadedpage-lifecycle

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 (on window): everything, including images, stylesheets and iframes, has loaded.
  • Scripts with defer or type="module" run just before DOMContentLoaded, so they rarely need either event.
  • visibilitychange reports when the tab is hidden or shown: save state and pause work there.
  • pagehide fires when the page is going away; beforeunload can ask "Leave site?" when there are unsaved changes.

The Loading Sequence

Stepdocument.readyStateEvent
HTML is being parsed"loading"
Parsing finished; defer and module scripts run"interactive"DOMContentLoaded on document
Images, stylesheets, iframes finished"complete"load on window
sequence.html
<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>
Output
script runs, readyState: loading
DOMContentLoaded, readyState: interactive
load, readyState: complete

Explanation: 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:

dom-ready.html
<!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>
Output
in head: null
after parse: $530

In 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:

index.html
<head>
  <script src="app.js" defer></script>
  <!-- or -->
  <script type="module" src="app.js"></script>
</head>
ScriptRunsNeeds DOMContentLoaded?
<script> at the end of <body>When reached, DOM above it is readyNo
<script> in <head>Immediately, before the body existsYes
<script defer>After parsing, in orderNo
<script type="module">After parsing, in order (deferred by default)No
<script async>As soon as it downloads, any orderMaybe (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:

when-ready.js
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:

image-load.html
<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>
Output
logo loaded: 1 x 1
image failed to load

Attach 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":

visibility.js
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

EventFiresUse for
pagehideThe page is being left (navigation, closing); may be kept in the back/forward cacheFinal cleanup; event.persisted is true if it may come back
pageshowThe page is shown, including when restored from the back/forward cacheRefreshing data after "Back"
beforeunloadBefore leaving, while it can still be canceledWarning about unsaved changes
beforeunload.js
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:

lifecycle.html
<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>
Output
New note | readyState: interactive
unsaved: true

Storage (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
when-ready.html
<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>
Output
first: ready
second: ran immediately

Quick check: Page load events

3 questions
1When does DOMContentLoaded fire?
2Why don't defer and module scripts need DOMContentLoaded?
3What is the most reliable moment to save a draft before the user leaves?

Key Takeaways

MomentUse
DOM readydefer / module, or DOMContentLoaded
Everything loadedwindow load
Image loaded or failedimg load / error
Tab hiddenvisibilitychange
Unsaved changes warningbeforeunload with preventDefault()

Was this tutorial helpful?

Lesson 77 of 139