Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Use JavaScript to detect what idle browser tabs can do

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article shows you what you can do with the JavaScript detection idle browser tab, the content is concise and easy to understand, it will definitely brighten your eyes. I hope you can learn something through the detailed introduction of this article.

In some cases, when users interact with our final product or application, we find ourselves performing a lot of intensive, CPU-intensive tasks. Starting a poller, establishing a WebSocket connection, or even loading media such as videos or pictures can be a performance handicap, especially if these tasks consume resources unnecessarily. It is a very good and meaningful practice to release the main thread from unnecessary workloads or network requests while the user does not actively interact with the interface. Alternatively, in an industry where most hosting providers are introducing quota-based pricing, reducing network requests can also reduce the cost of running applications or services.

Page visibility (Page Visibility) API

All modern web browsers add page visibility API, which allows us to detect when the browser's tabs are hidden, and we can register an event listener to detect signals when visibility changes.

Document.visibilityState

When the page is in the foreground, the document.visibilityState may be visible, minimizing the "tag" or hiding of the window.

We can access document.visibilityState directly in the following ways:

Console.log (document.visibilityState); / / = > it can be "visible" or "hidden"

Visibilitychange Event

We can also use event listeners to easily detect changes in the visibility properties.

Const onVisibilityChange = () = > {if (document.visibilityState = 'hidden') {console.log (' > this window is hidden.');} else {console.log ('> this window is visible.');}}; document.addEventListener ('visibilitychange', onVisibilityChange, false)

The polling example considers a situation in which we are polling API for updates and want to avoid making unnecessary calls to idle users. A simplified example is as follows:

Const poll = () = > {const interval = 1500; let _ poller = null; const repeat = () = > {console.log (`~ Polling: ${Date.now ()}.`);}; return {start: () = > {_ poller = setInterval (repeat, interval);}, stop: () = > {console.log ('~ Poller stopped.'); clearInterval (_ poller);}};};} Const poller = poll (); poller.start (); const onVisibilityChange = () = > {if (document.visibilityState = 'hidden') {poller.stop ();} else {poller.start ();}}; document.addEventListener (' visibilitychange', onVisibilityChange, false)

Load asynchronously in the background

But sometimes we can accelerate the user's terminal experience by doing the opposite. Instead of canceling all jobs and requests, we can load external dependencies or assets asynchronously. In this way, when users come back, their final experience will be more "fulfilling" and richer.

Webpack

Using ES2015 dynamic import recommendations and appropriate Webpack configuration lists, we can easily load additional modules or assets in the background.

Let loaded = false; const onVisibilityChange = () = > {if (document.visibilityState = 'hidden') {/ / Aggresively preload external assets ans scripts if (loaded) {return } Promise.all ([import ('. / async.js'), import ('. / another-async.js'), import (/ * webpackChunkName: "bar-module" * / 'modules/bar'), import (/ * webpackPrefetch: 0 * /' assets/images/foo.jpg')] .then (() = > {loaded = true;});}} Document.addEventListener ('visibilitychange', onVisibilityChange, false)

Rollup

Rollup also supports dynamic import out of the box.

Let loaded = false; const onVisibilityChange = () = > {if (document.visibilityState = 'hidden') {/ / Aggresively preload external assets ans scripts if (loaded) {return;} Promise.all ([import ('. / modules.js'). Then (({default: DefaultExport, NamedExport})) = > {/ / do something with modules. })] .then (() = > {loaded = true;});}}; document.addEventListener ('visibilitychange', onVisibilityChange, false)

Preload with Javascript

In addition to using the bundler, we can use only a few lines of JavaScript to preload static resources (such as images).

Let loaded = false; const preloadImgs = (... imgs) = > {const images = []; imgs.map (url = > new Promise ((resolve, reject) = > {images [I] = new Image (); images [I] .src = url; img.onload = () = > resolve (); img.onerror = () = > reject ();});} Const onVisibilityChange = () = > {if (document.visibilityState = 'hidden') {/ / Aggresively preload external assets ans scripts if (loaded) {return } Promise.all (preloadImgs ('https://example.com/foo.jpg',' https://example.com/qux.jpg', 'https://example.com/bar.jpg')) .then () = > {loaded = true;}) .catch () = > {console.log (' > snap.') );}}; document.addEventListener ('visibilitychange', onVisibilityChange, false)

Micro interaction

Finally, an ingenious way to attract the user's attention is to change the icon dynamically, using only a few pixels to keep the interaction.

Const onVisibilityChange = () = > {const favicon = document.querySelector ('[rel= "shortcut icon"]'); if (document.visibilityState = 'hidden') {favicon.href =' / come-back.png';} else {favicon.href ='/ example.png';}}; document.addEventListener ('visibilitychange', onVisibilityChange, false); the above is what can be done using JavaScript to detect idle browsers. Have you learned any knowledge or skills? If you want to learn more skills or enrich your knowledge reserve, you are welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report