Brief introduction to Page Visibility API

Introduction

Web browsers today eat your device's RAM for breakfast, lunch, snack and dinner. Over the years, websites have gone from being simple documents to being applications loaded with interactivity. Dozens of libraries, endless JSON payloads... all this generates a consumption of resources that, as responsible developers, we are obliged to mitigate as much as possible.

What is the need to keep interactivity and tasks running when the user is not even looking?

Page Visibility API

The HTML5 API called Page Visibility (standardized some time ago), is responsible for notifying us through events when the user removes the focus of our web application, either by switching tabs, minimizing the browser or turning off the screen, among others.

Through these events we can control our application to help manage resources more efficiently. Some typical use cases include stopping videos, animations or image carousels, muting sounds or auto-pausing games.

The API adds two read-only properties to the document.

The first property is hidden and indicates with a boolean value whether the document is visible or not.

On the other hand, visibilityState is the property that provides a string with one of the four possible states:

  • visible: The document is at least partially visible.
  • hidden: The document is not visible.
  • prerender: The document has loaded but has not yet been viewed.
  • unloaded: The document is about to be closed by user action.

Using it

We can listen to state changes by adding a listener to events of type visibilitychange.

  • JavaScript
document.addEventListener('visibilitychange', () => {
  if (document.hidden) {
    // Document is not visible, stop interactivity.
  } else {
    // Document is visible again, resume interactivity.
  }
});

Conclusion

Compatibility as of today is virtually full, including Internet Explorer 11.

Page Visibility is a very simple and easy API that will help us to implement substantial improvements in our web applications. Users will surely appreciate it.

You can support me so that I can dedicate even more time to writing articles and have resources to create new projects. Thank you!