Sling Academy
Home/JavaScript/Detect Page Visibility Changes with the Page Visibility API in JavaScript

Detect Page Visibility Changes with the Page Visibility API in JavaScript

Last updated: December 13, 2024

In modern web applications, it's often necessary to track whether a user is actively viewing a web page. For example, you might want to pause an in-progress video or halt live data fetching when the browser tab becomes invisible to optimize performance and reduce unnecessary load. The Page Visibility API in JavaScript is designed precisely for this purpose, allowing developers to detect when a page is in the foreground or hidden from the user's view.

What is the Page Visibility API?

The Page Visibility API provides methods to determine if a web page is visible or hidden. It enables developers to build responsive and efficient user experiences by tuning functionality based on the user's focus on a page.

How to Use the Page Visibility API

The API consists of two main components:

  • document.hidden: A Boolean property that indicates whether the page is hidden.
  • visibilitychange: An event that's fired whenever the page visibility state changes.

Basic Page Visibility Example

Let’s start with a basic example to illustrate the use of the Page Visibility API. This code listens for visibility changes and logs a message when they occur.

document.addEventListener('visibilitychange', function() {
  if (document.hidden) {
    console.log('Page is hidden');
  } else {
    console.log('Page is visible');
  }
});

With this script, when you switch to a different browser tab or minimize the window, you will see “Page is hidden” printed in the console. As soon as you return to the tab, “Page is visible” will appear.

Implementing Real-world Use Cases

Here’s an example illustrating a more practical use case: pausing and resuming a video based on page visibility.

const videoElement = document.getElementById('my-video');

document.addEventListener('visibilitychange', function() {
  if (document.hidden) {
    videoElement.pause();
    console.log('Video paused because page is not visible');
  } else {
    videoElement.play();
    console.log('Video resumed as page is visible again');
  }
});

In this script, whenever the page visibility changes, the video playback state is toggled accordingly. When the page is hidden, the video pauses; when the page becomes visible again, the video resumes playing.

Determining Initial Page Visibility State

It’s often useful to know the visibility state of the page immediately upon loading. You can check document.hidden at page load to determine its initial state.

if(document.hidden) {
  console.log('Page initially loaded in a hidden state');
} else {
  console.log('Page initially loaded in a visible state');
}

By incorporating this check, your application can properly initialize resources or logic when the page loads based on its initial visibility state.

Handling Cross-Browser Compatibility

Although the Page Visibility API is well-supported across modern browsers, it's always a good practice to include compatibility checks, as older browsers may not have full support.

const hiddenProperty = document.hidden !== undefined ? 'hidden' :
                        document.msHidden !== undefined ? 'msHidden' :
                        document.webkitHidden !== undefined ? 'webkitHidden' : undefined;

const visibilityChangeEvent = hiddenProperty.replace(/hidden/i, 'visibilitychange');

document.addEventListener(visibilityChangeEvent, function() {
  if (document[hiddenProperty]) {
    console.log('Page is hidden');
  } else {
    console.log('Page is visible');
  }
}, false);

This snippet ensures that the API works across a variety of browser variants by replacing the event and property names based on what is available in the user's browser.

Conclusion

Using the Page Visibility API, developers can create more fluid and resource-efficient web applications by optimizing performance according to whether a page is visible. This not only enhances user experience by conserving resources but also improves the application’s overall performance, especially in resource-intensive operations like playing media and live data synchronization. Implementing the Page Visibility API may require handling various browser differences, but with some planning and cross-browser compatibility checks, these can be easily managed.

Next Article: Run Tasks Only When Visible Using the Page Visibility API in JavaScript

Previous Article: Improve App Responsiveness with JavaScript Network Information

Series: Web APIs – JavaScript Tutorials

JavaScript

You May Also Like

  • Handle Zoom and Scroll with the Visual Viewport API in JavaScript
  • Improve Security Posture Using JavaScript Trusted Types
  • Allow Seamless Device Switching Using JavaScript Remote Playback
  • Update Content Proactively with the JavaScript Push API
  • Simplify Tooltip and Dropdown Creation via JavaScript Popover API
  • Improve User Experience Through Performance Metrics in JavaScript
  • Coordinate Workers Using Channel Messaging in JavaScript
  • Exchange Data Between Iframes Using Channel Messaging in JavaScript
  • Manipulating Time Zones in JavaScript Without Libraries
  • Solving Simple Algebraic Equations Using JavaScript Math Functions
  • Emulating Traditional OOP Constructs with JavaScript Classes
  • Smoothing Out User Flows: Focus Management Techniques in JavaScript
  • Creating Dynamic Timers and Counters with JavaScript
  • Implement Old-School Data Fetching Using JavaScript XMLHttpRequest
  • Load Dynamic Content Without Reloading via XMLHttpRequest in JavaScript
  • Manage Error Handling and Timeouts Using XMLHttpRequest in JavaScript
  • Handle XML and JSON Responses via JavaScript XMLHttpRequest
  • Make AJAX Requests with XMLHttpRequest in JavaScript
  • Customize Subtitle Styling Using JavaScript WebVTT Integration