Skip to content

Page Visibility API

This lesson explains Page Visibility API with clear examples, use cases, and best practices so you can use HTML5 APIs confidently in real web applications.

HTML5 Page Visibility API Overview

The HTML5 Page Visibility API helps web applications detect whether the current page is visible to the user or running in a hidden background tab. This lets you pause work that does not need to continue when the page is not being actively viewed.

It is commonly used to pause videos, stop animations, reduce background polling, delay notifications, save battery life, and improve performance in browser tabs that are not currently active.

Feature Description
API Name Page Visibility API
Main Object document
Main Property document.visibilityState
Quick Check document.hidden
Main Event visibilitychange
Common Uses Pause media, reduce CPU usage, save battery, limit background tasks.

Basic Page Visibility Example

// HTML5 Page Visibility API

document.addEventListener(
  "visibilitychange",
  () => {
    if (document.hidden) {
      console.log("Page is now hidden.");
    } else {
      console.log("Page is now visible.");
    }
  }
);

This example listens for visibility changes and prints whether the current page is hidden or visible.

How Page Visibility API Works

Step Description Example Syntax
Check State Read the current visibility status of the document. document.visibilityState
Quick Boolean Check if the page is hidden. document.hidden
Listen for Changes Run code whenever tab visibility changes. document.addEventListener("visibilitychange", callback)
Pause Work Stop expensive actions while tab is hidden. clearInterval(timerId)
Resume Work Restart required tasks when the page becomes visible. startPolling()

Page Visibility States

Property Meaning Typical Use
visible The page is currently visible to the user. Resume timers, media, or live updates.
hidden The page is in a background tab, minimized, or covered by another app. Pause work and reduce network or CPU usage.
document.hidden Boolean shortcut that is true when page is hidden. Simple conditional checks in app logic.

Read Current Visibility State

function showVisibilityState() {
  console.log(
    "Current state:",
    document.visibilityState
  );

  console.log(
    "Is hidden:",
    document.hidden
  );
}

showVisibilityState();

Use document.visibilityState when you want a readable status string and document.hidden for quick true or false checks.

Pause Video When Tab Becomes Hidden

const video =
  document.querySelector("#lessonVideo");

document.addEventListener(
  "visibilitychange",
  () => {
    if (document.hidden) {
      video.pause();
    }
  }
);

This pattern prevents a video from continuing to play while the user is not looking at the tab.

Pause and Resume Polling Requests

let timerId = null;

function fetchNotifications() {
  console.log("Fetching latest notifications...");
}

function startPolling() {
  if (timerId) {
    return;
  }

  fetchNotifications();

  timerId =
    setInterval(fetchNotifications, 10000);
}

function stopPolling() {
  clearInterval(timerId);
  timerId = null;
}

document.addEventListener(
  "visibilitychange",
  () => {
    if (document.hidden) {
      stopPolling();
    } else {
      startPolling();
    }
  }
);

startPolling();

This is a common use case in dashboards, chat apps, and admin panels where background polling should not continue forever in an inactive tab.

Pause Animation Logic in Hidden Tabs

let animationId = null;

function animate() {
  console.log("Animating frame...");

  animationId =
    requestAnimationFrame(animate);
}

function stopAnimation() {
  cancelAnimationFrame(animationId);
  animationId = null;
}

document.addEventListener(
  "visibilitychange",
  () => {
    if (document.hidden) {
      stopAnimation();
    } else if (!animationId) {
      animate();
    }
  }
);

animate();

Browsers already optimize many hidden-tab operations, but adding your own pause and resume logic gives you more predictable control over animations and CPU usage.

Track Active Reading Time

let activeStartTime = Date.now();
let totalActiveTime = 0;

document.addEventListener(
  "visibilitychange",
  () => {
    if (document.hidden) {
      totalActiveTime +=
        Date.now() - activeStartTime;

      console.log(
        "Active reading time:",
        totalActiveTime,
        "ms"
      );
    } else {
      activeStartTime = Date.now();
    }
  }
);

Analytics systems can use Page Visibility to measure active user attention more accurately than relying only on page load time.

Feature Detection

function supportsPageVisibility() {
  return typeof document.hidden !== "undefined";
}

if (supportsPageVisibility()) {
  console.log("Page Visibility API supported.");
} else {
  console.log("Page Visibility API not supported.");
}

Always use feature detection before depending on an API in production code, especially when supporting older browsers.

Common Page Visibility API Use Cases

  • Pause video or audio when the user leaves the tab.
  • Stop polling APIs in hidden tabs.
  • Pause canvas, game, or animation loops.
  • Delay non-urgent UI updates until the page becomes active.
  • Measure active user engagement more accurately.
  • Reduce battery consumption on mobile devices.
  • Prevent duplicate work across multiple open tabs.

Page Visibility API Best Practices

  • Pause expensive work when the page becomes hidden.
  • Resume only the work that actually needs to restart.
  • Combine Page Visibility with timers, media, and network logic.
  • Keep the visible and hidden states easy to reason about.
  • Use feature detection before adding listeners.
  • Test behavior with multiple tabs, minimized windows, and mobile browsers.
  • Use visibility changes as a signal, not as your only app lifecycle control.

Common Page Visibility API Mistakes

  • Continuing network polling even when the page is hidden.
  • Assuming hidden means the user has closed the page.
  • Forgetting to resume work when the tab becomes visible again.
  • Running duplicate intervals after multiple visibility changes.
  • Using the API without browser support checks.
  • Relying on visibility state alone for security-sensitive logic.

Page Visibility API vs Window Focus

Feature Page Visibility API Window Focus Events
Main Purpose Detect whether page is visible or hidden. Detect whether the browser window gains or loses focus.
Main Signal visibilitychange focus and blur
Best For Background tab optimization. Input and interaction handling.
Common Example Pause polling when tab is hidden. Highlight UI when window is active.

Key Takeaways

  • The Page Visibility API tells you when a page becomes visible or hidden.
  • Use document.visibilityState and document.hidden to read the current state.
  • Listen for visibilitychange to pause or resume app behavior.
  • The API is useful for media, polling, analytics, and performance optimization.
  • Combine it with clear pause and resume logic to avoid wasted work.

Pro Tip

If your app uses intervals, polling, media playback, or animation loops, Page Visibility is one of the simplest ways to improve performance without changing your full architecture.