Javascript is visible event

A look at the Page Visibility API

The Page Visibility API is a browser-based interface that tells your JavaScript application if the page is visible to the user or in the background.

The API is very simple and provides an event ( visibilitychange ) and two properties that are accessible via document object ( document.hidden and document.visibilityState ).

The API is widely supported in all major browsers (even IE10 and IE11):
https://caniuse.com/#feat=pagevisibility

The Page Visibility API is especially useful for saving resources and improving performance by letting a page avoid performing unnecessary tasks when the document isn’t visible. When the user minimizes the browser or switches to another tab, the API emits the visibilitychange event. The same event is emitted when the user restores the browser from the minimized state or changes to the tab where your application is running.

Depending on the visibility state, your application can perform some actions or behave differently. If your application plays a video or music, it can automatically pause the video or music when the user puts the tab into the background, and resume when the user returns to the tab. Another use case is to stop sending poll requests to a server when the page is in the background. Your application could suspend a WebSocket or EventSource connection and resume if the application is visible again, to save resources. Especially useful on mobile browsers where you have limited battery life and maybe limited data bandwidth, and it would make no sense to update a website if it’s not visible.

Читайте также:  Php yii console command

The following example listens for a change in visibility, changes the title of the page, and sends a request to a Spring Boot back end. This allows us to observe when the visibilitychange event is emitted.

document.addEventListener('visibilitychange', () => handleVisibility()); function handleVisibility()  if (document.visibilityState === 'hidden')  document.title = 'Visibility: hidden'; fetch('http://localhost:8080/hidden'); > else if (document.visibilityState === 'visible')  document.title = 'Visibility: visible'; fetch('http://localhost:8080/visible'); > > handleVisibility(); 

If you open the application in two tabs, you see that in the active tab, the property document.visibilityState is set to the value visible and in the inactive tab to hidden .

On a desktop browser, the event is emitted when you minimize and restore the browser. On a mobile browser, it is emitted when you press the home button and bring back the browser from the background, and it is also emitted when you press the power button to turn off the screen or to turn it on, while the browser is the active application.

The document.visibilityState property supports two additional values prerender and unload .

  • prerender : The page’s content is being prerendered and is not visible to the user.
  • unload : The page is in the process of being unloaded from memory.

Notice that both values are not supported in all browsers. The prerender state could be useful for web site analytics libraries to exclude these pages from the page visit counter. When a page is in the prerender state, the browser rendered the page only internally and is not visible to the user.

Visibility.js

When you use the Page Visibility API a lot in your application, you should take a look at the Visibility.js library. It’s a wrapper library that simplifies common tasks working with the Page Visibility API.

You add the library with npm install visibilityjs to an npm managed JavaScript project.

The library provides several methods that are accessible from the Visibility object.

The onVisible() method checks the current visibility state of the page. If the page is visible, it will run the callback; otherwise, the method waits until the visibility state changes to visible and then runs the callback. Notice that the callback is only executed once, even when the state changes multiple times from visible to hidden and back. Only the first time the page becomes visible, the callback method is executed.

Visibility.onVisible(() =>  console.log('onVisible event'); document.title = 'Visibility.js (visible)'; >); 

Next convenience method we take a look at is every() . It allows you to execute a callback periodically, but only when the page is visible.

This example prints out a text every second into the console, but only when the page is visible. As soon as you change the tab or minimize the browser every() stops and resumes when the state changes back to visible .

Visibility.every(1000, () => console.log('every 1000ms')); 

every() also supports a second interval parameter, which will be used when the page is hidden. In the next example, a GET request is issued every 15 seconds when the page is visible, and every 1 minute when the page is hidden.

Visibility.every(15 * 1000, 60 * 1000, s => fetch('http://localhost:8080/poll')); 

every() returns an identifier that can be used for stopping the timer. To cancel the timer, pass the identifier to the stop() method.

const everyTimer = Visibility.every(1000, () => console.log('every 1000ms')); setTimeout(() => Visibility.stop(everyTimer), 5000); 

Another method is change() which will install a listener function that is called each time the visibility state changes.

Visibility.change((e, state) =>  console.log('change event', state); updateTitle(); >); updateTitle(); function updateTitle()  if (Visibility.hidden())  document.title = 'Visibility.js (hidden)'; > else  document.title = 'Visibility.js (visible)'; > > 

Visibility.hidden() returns false when the visibility state is visible and returns true when the state is either hidden or prerender .

Visibility.state() returns a string with the current visibility state. This method returns the same string values as document.visibilityState .

This was just a quick overview of the Visibility.js library.
For a detailed description check out the project page: https://github.com/ai/visibilityjs

This concludes our tour around the Page Visibility API. A simple browser-based interface that is supported in all modern browsers and gives your application access to the visibility state of your page.

Источник

Page Visibility API

The Page Visibility API provides events you can watch for to know when a document becomes visible or hidden, as well as features to look at the current visibility state of the page.

This is especially useful for saving resources and improving performance by letting a page avoid performing unnecessary tasks when the document isn’t visible.

Concepts and usage

When the user minimizes the window or switches to another tab, the API sends a visibilitychange event to let listeners know the state of the page has changed. You can detect the event and perform some actions or behave differently. For example, if your web app is playing a video, it can pause the video when the user puts the tab into the background, and resume playback when the user returns to the tab. The user doesn’t lose their place in the video, the video’s soundtrack doesn’t interfere with audio in the new foreground tab, and the user doesn’t miss any of the video in the meantime.

Visibility states of an are the same as the parent document. Hiding an using CSS properties (such as display: none; ) doesn’t trigger visibility events or change the state of the document contained within the frame.

Use cases

Let’s consider a few use cases for the Page Visibility API.

  • A site has an image carousel that shouldn’t advance to the next slide unless the user is viewing the page
  • An application showing a dashboard of information doesn’t want to poll the server for updates when the page isn’t visible
  • A page wants to detect when it is being prerendered so it can keep accurate count of page views
  • A site wants to switch off sounds when a device is in standby mode (user pushes power button to turn screen off)

Developers have historically used imperfect proxies to detect this. For example, watching for blur and focus events on the window helps you know when your page is not the active page, but it does not tell you that your page is actually hidden to the user. The Page Visibility API addresses this.

Note: While onblur and onfocus will tell you if the user switches windows, it doesn’t necessarily mean it’s hidden. Pages only become hidden when the user switches tabs or minimizes the browser window containing the tab.

Policies in place to aid background page performance

Separately from the Page Visibility API, user agents typically have a number of policies in place to mitigate the performance impact of background or hidden tabs. These may include:

  • Most browsers stop sending requestAnimationFrame() callbacks to background tabs or hidden s in order to improve performance and battery life.
  • Timers such as setTimeout() are throttled in background/inactive tabs to help improve performance. See Reasons for delays longer than specified for more details.
  • Browsers implement budget-based background timeout throttling. This operates in a similar way across modern browsers, with the details being as follows:
    • In Firefox, windows in background tabs each have their own time budget in milliseconds — a max and a min value of +50 ms and -150 ms, respectively. Chrome is very similar except that the budget is specified in seconds.
    • Windows are subjected to throttling after 30 seconds, with the same throttling delay rules as specified for window timers (again, see Reasons for delays longer than specified). In Chrome, this value is 10 seconds.
    • Timer tasks are only permitted when the budget is non-negative.
    • Once a timer’s code has finished running, the duration of time it took to execute is subtracted from its window’s timeout budget.
    • The budget regenerates at a rate of 10 ms per second, in both Firefox and Chrome.

    Some processes are exempt from this throttling behavior. In these cases, you can use the Page Visibility API to reduce the tabs’ performance impact while they’re hidden.

    • Tabs which are playing audio are considered foreground and aren’t throttled.
    • Tabs running code that’s using real-time network connections (WebSockets and WebRTC) go unthrottled in order to avoid closing these connections timing out and getting unexpectedly closed.
    • IndexedDB processes are also left unthrottled in order to avoid timeouts.

    Extensions to other interfaces

    Instance properties

    The Page Visibility API adds the following properties to the Document interface:

    Returns true if the page is in a state considered to be hidden to the user, and false otherwise.

    A string indicating the document’s current visibility state. Possible values are:

    The page content may be at least partially visible. In practice this means that the page is the foreground tab of a non-minimized window.

    The page’s content is not visible to the user, either due to the document’s tab being in the background or part of a window that is minimized, or because the device’s screen is off.

    Events

    The Page Visibility API adds the following events to the Document interface:

    Fired when the content of a tab has become visible or has been hidden.

    Examples

    Pausing audio on page hide

    This example pauses audio when the user switches to a different tab, and plays when they switch back.

    HTML

    audio controls src="https://mdn.github.io/webaudio-examples/audio-basics/outfoxing.mp3">audio> 

    JavaScript

    const audio = document.querySelector("audio"); // Handle page visibility change: // - If the page is hidden, pause the video // - If the page is shown, play the video document.addEventListener("visibilitychange", () =>  if (document.hidden)  audio.pause(); > else  audio.play(); > >); 

    Result

    Try playing the audio, then switching to a different tab and back again.

    Specifications

    Browser compatibility

    BCD tables only load in the browser

    Found a content problem with this page?

    This page was last modified on Feb 19, 2023 by MDN contributors.

    Your blueprint for a better internet.

    MDN

    Support

    Our communities

    Developers

    Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
    Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.

    Источник

Оцените статью