Miscellaneous: HTML 5 page visibility API, miscellaneous api

Source: Internet
Author: User

Miscellaneous: HTML 5 page visibility API, miscellaneous api

Http://www.ido321.com/1126.html.

Original article: HTML5 Page Visibility API

Translation: HTML 5 page visibility API

Translator: dwqs

 

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

Why is the Page Visibility API introduced?

Previously, it was impossible to determine which tab was activated and which was not activated. However, with the help of the HTML 5 Visibility API, we can check whether users are browsing the page of a website.

In this article, we will understand how to use the HTML 5 Visibility API and use a small demo to check the page status. In this demo, the document title is displayed based on the page visibility status.

Check page visibility

To use the Visibility API, we need to first understand two new document attributes. 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 invisible on any screen.

2. prerender: the page is being loaded and invisible to users.

3. visible: the page is visible.

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

Document. hidden is a Boolean value. false indicates that the page is visible, and true indicates that the page is invisible.

Now that you know the available attributes, it is time to listen to events, so that you can know the page visibility status. This is

The visibilitychange event is used as an example:

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-to check the status of the current page. However, you must know that all attributes and methods must have a prefix, because they have a private prefix 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 < browserPrefixes.length; i++) {    var prefix = browserPrefixes[i] + 'Hidden';    if (prefix in document) {      return browserPrefixes[i];    }  }   // The API is not supported in browser.  return null;} // Get Browser Specific Hidden Propertyfunction hiddenProperty(prefix) {  if (prefix) {    return prefix + 'Hidden';  } else {    return 'hidden';  }} // Get Browser Specific Visibility Statefunction visibilityState(prefix) {  if (prefix) {    return prefix + 'VisibilityState';  } else {    return 'visibilityState';  }} // Get Browser Specific Eventfunction visibilityEvent(prefix) {  if (prefix) {    return prefix + 'visibilitychange';  } else {    return 'visibilitychange';  }}

 

Now, with all browser attributes and methods with a prefix, you can safely apply them. Make adjustments to the previous Code:

// 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 does the Visibility API need to be used?

You can consider using APIs in the following situations: 1. You are browsing a navigation page, and the page is querying details from an RSS source, or calling the API regularly, if the page is invisible to users, we can restrict calls to RSS sources or APIs. 2. for common hand style effects, you can restrict the movement of pages when they are invisible. 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 the Demo.

Demo

Demo1: Use the Visibility API to change the page title: View Demo Demo2: How to query the data transferred from the server from the restriction when the page is invisible. In Demo2, how do we limit queries for Refresh information from the server? Not only is the user browsing the page, but it is assumed that JQuery has been introduced to the page. To make it simple, it only indicates the count, but can be replaced by Real Server data.

HTML:

<!-- This element will show updated count -->

 

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 suggest you go to Can I use? To query. However, it is recommended that you use programming methods to check whether the browser supports these Features. for details, see Detect Support for varous HTML5 Features:

Http://www.ido321.com/1116.html ). This API has been well supported in mainstream modern browsers.

 

Summary

As I said, there is a very good API that contains two attributes and an event for us to use. It can be easily integrated into your existing applications and bring a good user experience. Finally, we can control the page behavior when the page is invisible to users.

Next article: Miscellaneous: Message notification mechanism of HTML 5


What is API? What is HTML5 API? Is it easy to understand? Do not copy

Application interface. When developing a program, we need to call the api. Why do we need to call the api? Because many system operations cannot be completed by writing programs by ourselves, we need to call the methods written by others. This method is the api provided by others. For example, to obtain the browser version, we only need to call a method about version to obtain the version information. How can we get the version information written at the lower layer. Similarly, in HTML5, getElementById () is an api. If you do not provide this method, you cannot obtain a dom element. Therefore, querying the api documentation is to look up the methods written by others.

Special marquee text effects

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.