Optimize UX and Performance with the Page Visibility API

clock icon June 6, 2019

Tabbed browsing is great as it helps a user switch between different tabs which contain the information they care about. However, the user can only look at one tab at a time so optimizing your web experience to make sure it does not interfere with the goals of the user is important. As the Next Billion Users hit the web for the first time, many of them live in regions with unreliable infrastructure and use low-end devices. They may also be on flakky/limited bandwidth and keeping this in mind is good for both the user and the business. The user ends up gets a smooth experience and the business is able to get more users by providing better service.


As mentioned earlier, a user can only see one thing at a time so your web app’s background experience is as important as the foreground experience. Detecting the state of your web app (foreground or background) is something that can be easily achieved with the Page Visibility API.


Page Visibility API

As quoted from W3C spec, the page visibility API “defines a means to programmatically determine the visibility state of a top-level browsing context, and to be notified if the visibility state changes.” This means, work can be scaled down while the web app is in a background tab (hidden) and scaled up when it is in foreground (visible). This not only optimizes the performance of the web app, but can also be used to make runtime decisions that improve the overall user experience. Using the API is quite straight forward:

// listen for the visibilitychange event
document.addEventListener('visibilitychange', handleVisibilityChange, false);

// Handle page visibility change events
function handleVisibilityChange() {
  if (document.visibilityState === "hidden") {
    // scale down work
  } else {
    // scale up work
  }
}

A Few Use Cases

The API can be used in a couple of scenarios:

  • A video playing site can pause a video when the user switches to another tab since videos require user attention and resume when the user switches back
  • A real-time application can reduce the intervals which it queries the server for new data i.e. instead of sending requests every second, it could send every 5 minutes.
  • Stop a fancy animation to save device resources while the page is in the background


Browser Support

Browser support is quite good and goes as far back as IE 10. A support table can be found below:

Browser support table for Page Visibility API


Fallback Mechanisms

In the past, developers have used the blur and focus events to achieve the same results. Though imperfect solutions, they can be used in older browsers where the page visibility API is not supported. An example of usage would be like so:

if (document.visibilityState) {
  // use page visibility API
}
else {
  window.addEventListener(‘blur’, handleWindowBlur);
  window.addEventListener(focus, handleWindowFocus);
}

Useful Links