DEV Community

Cover image for How the Page Visibility API Improves Web Performance and User Experience
Sachin Chaurasiya
Sachin Chaurasiya

Posted on • Originally published at blog.sachinchaurasiya.dev

How the Page Visibility API Improves Web Performance and User Experience

Making web applications fast and user-friendly is very important today. One useful tool for this is the Page Visibility API. This API tells developers if a web page is visible to the user or hidden in the background. It helps manage resources better and improve user interactions. In this article, we'll look at what the Page Visibility API is, why it matters, how to use it, some example use cases, and how to integrate it with ReactJS.

What is the Page Visibility API?

The Page Visibility API is a web tool that lets developers check if a web page is visible or hidden. It has properties and events that notify when a page becomes visible or hidden, so developers can change how the app behaves.

Key Concepts

  • document.visibilityState: This property shows if the document is visible or not. Possible values include:

    • visible: The page is visible to the user.
    • hidden: The page is not visible to the user.
  • visibilitychange Event: This event occurs whenever the document's visibility state changes.

Why Use the Page Visibility API?

Performance Optimization

When a web page is not visible, it's smart to reduce or stop heavy tasks like animations, video playback, or data polling. This saves CPU and battery life, especially on mobile devices.

User Experience Improvement

By knowing when a user is not looking at the page, you can pause things like video playback or game animations. This way, the user won't miss any content. When the user comes back, you can resume these activities, making the experience smooth.

Accurate Analytics

Tracking visibility changes helps gather more accurate usage data. Knowing when users switch tabs or minimize windows provides better insights into user behavior.

How to Use the Page Visibility API?

Using the Page Visibility API in plain JavaScript is simple. Here’s a basic example

document.addEventListener('visibilitychange', function() {
  if (document.visibilityState === 'visible') {
    console.log('Page is visible');
    // Resume activities
  } else {
    console.log('Page is not visible');
    // Pause activities
  }
});
Enter fullscreen mode Exit fullscreen mode

In this example, an event listener is attached to the visibilitychange event. Depending on the visibility state, appropriate actions are taken.

Using the Page Visibility API with ReactJS

To use the Page Visibility API in a React application, you can create a custom hook that encapsulates the logic.

import { useEffect, useState } from 'react';

const usePageVisibility = () => {
  const [isVisible, setIsVisible] = useState(!document.hidden);

  const handleVisibilityChange = () => {
    setIsVisible(!document.hidden);
  };

  useEffect(() => {
    document.addEventListener('visibilitychange', handleVisibilityChange);

    return () => {
      document.removeEventListener('visibilitychange', handleVisibilityChange);
    };
  }, []);

  return isVisible;
};

export default usePageVisibility;
Enter fullscreen mode Exit fullscreen mode

You can then use this custom hook within a React component

import React, { useEffect } from 'react';
import usePageVisibility from './usePageVisibility';

const MyComponent = () => {
  const isVisible = usePageVisibility();

  useEffect(() => {
    if (isVisible) {
      console.log('Component is visible');
      // Resume activities
    } else {
      console.log('Component is not visible');
      // Pause activities
    }
  }, [isVisible]);

  return (
    <div>
      {isVisible ? 'Page is visible' : 'Page is not visible'}
    </div>
  );
};

export default MyComponent;
Enter fullscreen mode Exit fullscreen mode

This approach ensures that your React components can respond to visibility changes efficiently, improving the overall user experience.

Example Use Cases

Video Streaming Services

Platforms like YouTube and Netflix use the Page Visibility API to pause videos when users switch tabs or minimize the browser. This way, users don't miss any content and it saves bandwidth and system resources.

Online Games

Online games can pause the game when the tab is not active. This prevents users from losing progress or missing important events in the game. It also helps save system resources and improve performance.

Data Fetching and Polling

Web applications that often fetch data from a server can slow down or stop polling when the page is not visible. This cuts down on unnecessary network requests and uses resources more efficiently.

Best Practices

Performance Considerations

When using the Page Visibility API, make sure that any paused activities resume efficiently. Avoid unnecessary state changes and resource loading to maintain good performance.

Error Handling

Always include error-handling mechanisms to manage unexpected issues or browser limitations. This helps maintain a smooth user experience, even in rare cases.

User Notifications

Consider letting users know when activities are paused because of visibility changes, especially for important tasks like video calls or gaming. This transparency can boost user trust and satisfaction.

Conclusion

The Page Visibility API helps make web apps better by adjusting to the user's focus. With this API, developers can improve performance, enhance user experience, and get accurate analytics. Whether you're using plain JavaScript or React, the Page Visibility API is very useful for modern web development.

That's all for this topic. Thank you for reading! If you found this article helpful, please consider liking, commenting, and sharing it with others.

Resources

  1. MDN Web Docs on Page Visibility API

  2. Can I use: Browser Support for Page Visibility API

  3. Test Page Visibility API

Connect with me

Top comments (2)

Collapse
 
myogeshchavan97 profile image
Yogesh Chavan

Thanks for sharing. This API is really useful. Even Tanstack Query(React Query) uses it to refetch the data, once the window is focused

Collapse
 
sachinchaurasiya profile image
Sachin Chaurasiya

Glad you found it useful.