This is the sixth day of my participation in the August More text Challenge. For details, see:August is more challenging

preface

In Chrome, each page TAB is a process, and when it is invisible for a certain period of time, it is hibernated to save system resources such as memory. During development, we sometimes need to check whether the user is on the current page to meet functional requirements.

In the past, judging whether a user is in the current page is usually judged by pageHide, beforeUnload, and beforeunload events, but not all of them are triggered on the mobile side, because the current page is switched to another application by the system, and the system kills the browser process, which cannot be monitored. When a user switches an application and then runs out of memory or has not been used for too long, the system will kill the browser process directly and unload and beforeUnload will not be triggered in time.

The Page Visibility API monitors Page Visibility changes in all cases, whether mobile or desktop. Using it can enhance the user experience, when the user is not in the current page, can stop audio and video playback, network requests, animation loading, etc., to save resources and power.

Interface features

The Page Visibility API methods and properties are mounted to the Document object, which we can call at any time. It has the following properties:

  • document.hidden: Whether the window is invisible, read-only property, true if the window is completely invisible
  • document.visibilityState: read-only property, indicating the state of the current window:'hidden' | 'visible' | 'prerender', as long as the current page is even slightly visibletrue.
  • visibilitychange: Event type, fired when the visibility of the window changes.

Document. visibilityState is recommended instead of document.hidden, which can detect not only the visibility of the page but also whether the page is pre-rendered.

document.hidden

Read-only property that returns a Boolean value indicating whether the page is visible or not. True means it is not visible at all.

document.visibilityState

Document. visibilityState can detect more complex scenes than document.hidden. It has three status values:

  • hidden: The page is completely invisible.
  • visible: At least part of the page is visible.
  • prerender: The page is about to be rendered and is not visible.

The prerender state is only used in browsers that support pre-rendering. Chrome has a prerender feature that renders a page before the user sees it and then displays the rendered page when the user wants to view it.

The following cases are hidden:

  • Browser minimization.
  • The browser is not minimized, but the current page switches to another page.
  • The browser is about to uninstall (unload) page.
  • System screen lock.

The four scenarios above cover all the scenarios in which a page might be unloaded. With the exception of hidden and prerender, any page that appears is visible at all times.

Before the page is uninstalled, document.visibilityState must be hidden, which is why the W3C designed this API.

visibilitychange

The VisibilityChange event is triggered whenever the document.visibilityState property changes. Therefore, you can detect changes in page visibility by listening for this event.

document.addEventListener("visibilitychange".() = >{
   if(document.visibilityState==="hidden") {console.log("Page not visible")}else{
       console.log("Page visible")}})Copy the code

The document.visibilityState property is only for the top-level window. The document.visibilityState property of the embedded

MDN description:

The visibility status of the

Usage scenarios

Save audio flow

When the user leaves the current page, we can pause the audio and video playback to save the user traffic.

<video id="video">
  <source id='mp4' src="movie.mp4" type='video/mp4'/>
</video>
Copy the code
const onVisibilityChange = () = > {
  const video = document.getElementById("video");
  // Pause when the page is completely invisible, and resume when it is visible
  return document.hidden
    ? video.pause()
    : video.play();
}

document.addEventListener("visibilitychange", onVisibilityChange);
Copy the code

Demo: Page Visibility API (daniemon.com)

Lazy resource loading

In addition to saving traffic, we can also implement lazy loading of resources in conjunction with webPack’s dynamic loading module import(). For example, when the user leaves the current page, we can request and cache resources that the user may use next to improve the experience.

let loaded = false;
const onVisibilityChange = () = > {
  if(! loaded &&document.visibilityState === 'visible') {
    Promise.all([
      import(/* webpackChunkName: "bundle-[index]"*/ './dist'),
      import(/* webpackPrefetch: 0 */ './images')
    ]).then(() = > {
      loaded = true; }); }};document.addEventListener('visibilitychange', onVisibilityChange);
Copy the code

other

In addition to the above scenarios, you can also use them to turn off timers, suspend webSocket polling, stop page animations, and more, all of which can further improve page performance and user experience.

conclusion

The interface is now widely supported, and the Web Performance Working Group advocates that we use the API when building applications to improve application Performance and user experience.

reference

  • Page visibility API – Web API interface reference | MDN (mozilla.org)
  • Page Visibility Level 2 (w3.org)
  • Using the PageVisibility API – HTML5 Rocks
  • How to Detect Idle Browser Tabs with the Page Visibility API (alligator.io)
  • Code Splitting | webpack

The articles

  • More powerful File interface, File System Access API
  • What, web pages can communicate directly with hardware? Web Serial API! | August More text Challenge (juejin.cn)
  • The Stream API in JS in 5000 words will help you fully understand the Stream API in JS.
  • Overview of the Current Interface between Web and peripheral Hardware (Juejin.cn)