Knowing when nobody is looking
The Page Visibility API tells you whether your page is currently visible or hidden, for example when the user switches tabs or minimises the window. This lets apps behave politely with resources.
- document hidden is a boolean shortcut, true when not visible
- document visibilityState is visible or hidden
- The visibilitychange event fires whenever the state changes
Practical wins
- Pause video, audio, or animations when hidden
- Stop polling or expensive timers to save battery and data
- Save draft state when the user leaves the tab
- Resume activity when the page becomes visible again
A note on reliability
For saving important data before a tab closes, pair visibilitychange with care, since the unload event is unreliable on mobile. Many teams treat the page becoming hidden as the last safe moment to persist state.
Key idea
The Page Visibility API exposes document hidden and the visibilitychange event so apps pause expensive work and persist state when a tab is no longer visible.