Page Visibility API: Save Battery with document.hidden

The Page Visibility API provides web developers with a built-in mechanism to determine whether a webpage is currently visible to the user or running in the background. By utilizing the document.hidden property and the visibilitychange event, JavaScript can intelligently pause resource-heavy operations like animations, timers, and network requests when a user switches tabs or minimizes a browser window. This proactive management significantly reduces CPU usage and memory consumption, directly conserving battery life on mobile and desktop devices.

What is the Page Visibility API?

Historically, developers relied on window blur (window.onblur) or focus (window.onfocus) events to detect user engagement. However, these events only indicate if the window has active focus, not if the page is actually visible on the screen.

The Page Visibility API solves this by exposing the true rendering state of the document through two primary properties and one event:

How document.hidden Conserves Battery Life

When users open multiple browser tabs, background tabs often continue executing background scripts. Unmonitored JavaScript execution drains battery power through continuous CPU and GPU cycles. Using document.hidden mitigates power consumption in several ways:

  1. Pausing Animations and Video Playback
    Canvas renderings, WebGL scenes, CSS animations, and HTML5 video streams require constant frame updates. Halting these visual processes when document.hidden is true stops redundant GPU rendering pipelines.

  2. Throttling Network Polling
    Applications that use setInterval or setTimeout to fetch real-time updates (like chat apps, live scoreboards, or stock tickers) waste network radio power when a user is not looking. Checking document.hidden allows developers to pause polling or lower the fetch frequency until the tab becomes active again.

  3. Suspending High-Frequency Timers
    JavaScript timers keep the CPU awake. By clearing active intervals during hidden states, the processor can enter low-power sleep states more frequently.

Practical Implementation

Implementing the Page Visibility API requires attaching an event listener to the document to observe visibility changes:

function handleVisibilityChange() {
  if (document.hidden) {
    // Page is hidden: pause animations, stop audio/video, halt polling
    pauseVideoPlayback();
    stopLiveMetricsPolling();
  } else {
    // Page is visible: resume tasks
    resumeVideoPlayback();
    startLiveMetricsPolling();
  }
}

document.addEventListener("visibilitychange", handleVisibilityChange);

By leveraging document.hidden, web applications operate efficiently, minimizing unnecessary computations in the background and extending the battery lifespan of client hardware.