JavaScript Reference ยท Browser and Web APIs
Page visibility and lifecycle
Concept page on page visibility and lifecycle in JavaScript: visibilitychange, pagehide, pageshow, beforeunload and IntersectionObserver, with live examples.
A page does not just load and stay there. The user switches tabs, minimizes the window, locks the phone, scrolls an element out of view, navigates away, or comes back through the browser's Back button. Browsers expose these changes as events and observers so you can pause work nobody can see, save state before it is lost, and load things only when they matter.
There are two different questions. "Is this whole page visible?" is answered by the Page Visibility API. "Is this particular element visible?" is answered by IntersectionObserver. A third group of events, pagehide, pageshow and friends, covers the page's life cycle from load to departure.
Is the page visible?
document.visibilityState is "visible" or "hidden" (document.hidden is the boolean shortcut). The visibilitychange event fires on document whenever it changes. Hidden pages are throttled by browsers, so stop animations, polling and video there.
Is this element visible?
new IntersectionObserver(callback, options) watches elements and calls you when the fraction of an element inside the viewport (or another root) crosses a threshold. It runs off the main scroll path, so it replaces slow scroll-handler measurements for lazy loading, "reveal on scroll" effects and analytics.
The page life cycle
DOMContentLoadedfires when the HTML has been parsed and deferred scripts have run;loadfires when images and other resources have finished.pagehidefires when the page is being left, including when it goes into the browser's back/forward cache (thepersistedproperty of the event istruethen).pageshowfires on load and when the page is restored from that cache, so use it to refresh stale data.visibilitychangeto"hidden"is the most reliable moment to save work or send analytics, because it also fires on mobile when the user switches apps, a case where other events may never arrive.beforeunloadlets you ask the browser to show a "leave this page?" confirmation (event.preventDefault()), but browsers only honor it after the user has interacted with the page, and it can block the back/forward cache. Add it only while there are really unsaved changes, and remove it afterwards.unloadis deprecated and unreliable. Do not use it; usepagehideorvisibilitychange.freezeandresumeare newer events in some browsers for pages that the browser suspends in the background.
To send data as the user leaves, use navigator.sendBeacon(url, data) or fetch(url, { keepalive: true }) from a visibilitychange or pagehide handler, since ordinary requests may be cancelled.
Usage notes
- Hidden does not mean closed. A hidden page may later become visible again; pause, do not tear down.
- Pick the right tool. Use
IntersectionObserverfor elements,visibilitychangefor the whole page. - Thresholds:
threshold: 0fires on the first pixel,1only when fully visible, and an array such as[0, 0.25, 0.5, 1]fires at each step. rootMargingrows or shrinks the root box, such as"200px"to start loading images before they scroll into view.- Call
unobserve()ordisconnect()once an element no longer needs watching, to free resources. - The initial callback always fires after
observe(), so the first entry may reportisIntersecting: false.
Browser support
The Page Visibility API and IntersectionObserver are supported in all current browsers. freeze and resume are only in some, and details of the back/forward cache differ between browsers, so test the behavior you rely on.
Related
- Vibration and other device APIs (wake lock)
- performance.now() and Performance API
- Web Workers
- Lessons: Observers, Events, Performance