search
HomeWeb Front-endHTML TutorialChat: HTML 5 page visibility API_html/css_WEB-ITnose

Translation source: http://www.ido321.com/1126.html

Original text: HTML5 Page Visibility API

Translation: HTML 5 pages can Visual API

Translator: dwqs

In the early days, browsers did not provide tabs, but now basically all browsers do this function. As a programmer, I usually have 10 to 15 tabs open at the same time, and sometimes 25 to 30.

Why introduce the Page Visibility API?

Before, it was impossible to determine which tab was active and which was not, but with the help of HTML 5 Visibility API, it is possible to detect whether the user is browsing a page of a website.

In this article, we will understand how to use the HTML 5 Visibility API and use a small demo to discover the status of the page. In this demo, the title of the document will pop up based on the visibility status of the page.

Check the visibility of the page

In order to use the Visibility API, we need to first understand two new document properties, the first is document.visibilityState and the other is document.hidden. Their functions are different.

document.visibilityState has four different values:

1. hidden: the page is not visible on any screen

2. prerender: the page is loading, not visible to the user Visible

3. visible: the page is visible

4. unloaded: the page is unloaded (that is, the user will leave the current page)

document.hidden is a Boolean value, false means the page Visible, true means the page is not visible.

Now that you know the available attributes, it’s time to listen for events, so that you can know what the visibility status of the page is. This is done using the visibilitychange event. The example is as follows:

document.addEventListener('visibilitychange', function(event) {  if (!document.hidden) {    // The page is visible.  } else {   // The page is hidden.  }});

This code is a simple application of the visibilitychange event? Detection The status of the current page. But what you must know is that all properties and methods must be prefixed because they are privately prefixed in some browsers. The following is a cross-browser case:

// Get Browser-Specifc Prefixfunction getBrowserPrefix() {     // Check for the unprefixed property.  if ('hidden' in document) {    return null;  }   // All the possible prefixes.  var browserPrefixes = ['moz', 'ms', 'o', 'webkit'];   for (var i = 0; i  <p> </p> Now that you have prefixed properties and methods in all browsers, you can apply them with confidence. Make adjustments to the previous code:  <p> </p> <p class="sycode"> </p><pre style="代码" class="precsshei">// Get Browser Prefixvar prefix = getBrowserPrefix();var hidden = hiddenProperty(prefix);var visibilityState = visibilityState(prefix);var visibilityEvent = visibilityEvent(prefix); document.addEventListener(visibilityEvent, function(event) {  if (!document[hidden]) {    // The page is visible.  } else {   // The page is hidden.  }});
Where do I need to use the Visibility API?

In the following situations, you can consider using the API:

1. You are browsing a navigation page, and this page is querying details from an RSS source, or calling it regularly API, if the page is not visible to users,

We can limit calls to RSS feeds or APIs.

2. For common hand-style effects, when the page is invisible, its movement can be restricted.

3. In the same way, HTML Notification (Translation: http://www.ido321.com/1130.html) is displayed to the user only when the page is invisible.

We already know how the code calls the Visibility API, let’s take a look at a Demo.

Demo

Demo1: Use the Visibility API to change the page title: View Demo

Demo2: When the page is not visible, how to limit the query from the server transmitted data.

In Demo2, how will we limit the query for refresh information from the server? Not only is the user browsing the page, but also assuming that the page has introduced

JQuery. For simplicity, only counts are shown, but real server data can be used instead.

HTML:

<!-- This element will show updated count --><h1 id="valueContainer">0</h1>

JavaScript:

<script type="text/javascript">         // Get Browser Prefix    var prefix = getBrowserPrefix();    var hidden = hiddenProperty(prefix);    var visibilityState = visibilityState(prefix);    var visibilityEvent = visibilityEvent(prefix);         var timer = null;         function increaseVal() {        var newVal = parseInt($('#valueContainer').text()) + parseInt(1);        $('#valueContainer').text(newVal);        document.title = newVal + ': Running';                 timer = setTimeout(function() {            increaseVal();        }, 1);    }         // Visibility Change    document.addEventListener(visibilityEvent, function(event) {          if (document[hidden]) {              clearTimeout(timer);              var val = parseInt($('#valueContainer').text());              document.title = val + ': Pause';          } else {              increaseVal();           }    });         increaseVal();     </script>

View Demo

Browser Support

If you want to know whether the browser supports the Visibility API, I recommend going to Can I use? to check. However, it is recommended to use programming to detect whether the browser supports it. You can refer to Detect Support for Various HTML5 Features (Translation:

http://www.ido321.com/1116.html). There is already good support for this API in mainstream modern browsers

Summary

As I said, there is a nice API for us to use that contains two properties and an event. It can be easily integrated into your existing applications and can bring a great user experience. The last thing I want to say is that when the page is invisible to the user, we can control the behavior of the page.

Next article: Miscellaneous talk: HTML 5 message notification mechanism

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
HTML, CSS, and JavaScript: Examples and Practical ApplicationsHTML, CSS, and JavaScript: Examples and Practical ApplicationsMay 09, 2025 am 12:01 AM

The roles of HTML, CSS and JavaScript in web development are: 1. HTML is used to build web page structure; 2. CSS is used to beautify the appearance of web pages; 3. JavaScript is used to achieve dynamic interaction. Through tags, styles and scripts, these three together build the core functions of modern web pages.

How do you set the lang attribute on the  tag? Why is this important?How do you set the lang attribute on the tag? Why is this important?May 08, 2025 am 12:03 AM

Setting the lang attributes of a tag is a key step in optimizing web accessibility and SEO. 1) Set the lang attribute in the tag, such as. 2) In multilingual content, set lang attributes for different language parts, such as. 3) Use language codes that comply with ISO639-1 standards, such as "en", "fr", "zh", etc. Correctly setting the lang attribute can improve the accessibility of web pages and search engine rankings.

What is the purpose of HTML attributes?What is the purpose of HTML attributes?May 07, 2025 am 12:01 AM

HTMLattributesareessentialforenhancingwebelements'functionalityandappearance.Theyaddinformationtodefinebehavior,appearance,andinteraction,makingwebsitesinteractive,responsive,andvisuallyappealing.Attributeslikesrc,href,class,type,anddisabledtransform

How do you create a list in HTML?How do you create a list in HTML?May 06, 2025 am 12:01 AM

TocreatealistinHTML,useforunorderedlistsandfororderedlists:1)Forunorderedlists,wrapitemsinanduseforeachitem,renderingasabulletedlist.2)Fororderedlists,useandfornumberedlists,customizablewiththetypeattributefordifferentnumberingstyles.

HTML in Action: Examples of Website StructureHTML in Action: Examples of Website StructureMay 05, 2025 am 12:03 AM

HTML is used to build websites with clear structure. 1) Use tags such as, and define the website structure. 2) Examples show the structure of blogs and e-commerce websites. 3) Avoid common mistakes such as incorrect label nesting. 4) Optimize performance by reducing HTTP requests and using semantic tags.

How do you insert an image into an HTML page?How do you insert an image into an HTML page?May 04, 2025 am 12:02 AM

ToinsertanimageintoanHTMLpage,usethetagwithsrcandaltattributes.1)UsealttextforaccessibilityandSEO.2)Implementsrcsetforresponsiveimages.3)Applylazyloadingwithloading="lazy"tooptimizeperformance.4)OptimizeimagesusingtoolslikeImageOptimtoreduc

HTML's Purpose: Enabling Web Browsers to Display ContentHTML's Purpose: Enabling Web Browsers to Display ContentMay 03, 2025 am 12:03 AM

The core purpose of HTML is to enable the browser to understand and display web content. 1. HTML defines the web page structure and content through tags, such as, to, etc. 2. HTML5 enhances multimedia support and introduces and tags. 3.HTML provides form elements to support user interaction. 4. Optimizing HTML code can improve web page performance, such as reducing HTTP requests and compressing HTML.

Why are HTML tags important for web development?Why are HTML tags important for web development?May 02, 2025 am 12:03 AM

HTMLtagsareessentialforwebdevelopmentastheystructureandenhancewebpages.1)Theydefinelayout,semantics,andinteractivity.2)SemantictagsimproveaccessibilityandSEO.3)Properuseoftagscanoptimizeperformanceandensurecross-browsercompatibility.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software