Home > Web Front-end > JS Tutorial > body text

HTML5: Explore the Web Information API

王林
Release: 2023-08-28 19:09:06
Original
808 people have browsed it

HTML5:探索网络信息 API

Introduction

One of the most discussed concepts in the field of web design is responsive web design. Thousands of articles have been written about responsive web design, so I won’t discuss it in this article. However, responsive web design has an important limitation. Responsive web design is mostly based on the size of the browser viewport.

While this method is great for delivering images of the correct size and resolution, it is not suitable for every situation, video content being one example. In these cases, what we really need is more information about the device's network connection.

Let's say you're accessing YouTube on your smartphone or tablet. You're at home and connected via Wi-Fi. In this case, you don't care about the number of bytes being downloaded, you are only interested in high-quality video content. This isn't the case if you're connecting over a slow mobile connection. In this case, you want to watch the video, quality is secondary.

I should be clear that every developer who wants their website to be truly great still has to optimize the resources it provides to allow the page to load as quickly as possible. However, in the above example, serving high-resolution video does not waste the user's bandwidth but improves the user experience.

The Network Information API is exactly where we need to know more about the device's network connection.

1.What is it?

The Network Information API provides access to the connection types that the system uses to communicate with networks, cellular networks, Wi-Fi, Bluetooth, and more. It also provides a way to notify the script when the connection type changes. This is to allow developers to make dynamic changes to the DOM and/or notify users that the network connection type has changed.

The Network Information API specification was first published in 2011, but the API has changed several times since then. As proof, the current version is only an editorial draft, which means changes are bound to occur in the future.

Despite these changes, the use cases for this API are very interesting and really worth exploring. In this article we will discuss the latest version of the specification, but we will also look at some deprecated properties and events for reasons I will explain later.

2.Implementation

The current version of the Network Information API exposes a connection object that belongs to the window.navigator object. The connection object contains one property, type, that returns the user agent's connection type. type The attribute can have one of the following values:

  • Bluetooth

  • cellular
  • Ethernet
  • none
  • wifi
  • other
  • unknown

Some of these values ​​are self-explanatory, such as bluetooth and wifi, while others require more explanation. cellular Type refers to the mobile connection, such as EDGE, 3G, 4G, etc. The other type indicates that the current connection type is not unknown, but it is not any other type either. The unknown type indicates that the user agent has established a network connection, but cannot determine what the connection type was.

In addition to type, the Network Information API also exposes the ontypechange event. It is triggered every time the network connection type changes.

Developers can use the Network Information API to change certain features based on the current connection type. For example, if we detect that a device is using a mobile connection, we can slow down bandwidth-intensive processes. The API also allows us to assign specific classes to html elements, such as high-bandwidth, in the same way as Modernizr. We can use CSS to change one or more properties of an element, such as the background image.

Now that we know what the Network Information API does and what we can benefit from, let's see which browsers support the API.

3.Browser support

As of this writing, the Network Information API is only supported by Firefox and Chrome Canary using its vendor prefix. In Chrome Canary, we must enable the Experimental Web Platform Features flag to use the API. You can find more information in this article by Paul Irish.

As if support for the Network Information API wasn't bad enough, the latest version of Firefox, version 30, supports the old API specification. Therefore, if you want to use the Network Information API now, be sure to review the properties and events exposed by the previous API specification.

The old specification exposed two properties: bandwidth and metered. bandwidth The property is a double value that represents an estimate of the current bandwidth in megabytes per second (MB/s). metered The property is a Boolean value that specifies whether the device's network connection is subject to any restrictions. The previous specification also defined the onchange event to notify any listeners of changes to the above properties.

To give you an idea of ​​the new and old versions of the specification, in the next section we will build a demo that uses both versions.

4. Demonstration

So far, we have introduced the properties and events exposed by the API as well as the use cases of the API. In this section, we'll create a simple web page to see the API in action.

The demo consists of an HTML5 page containing an unordered list of three list items. Each project contains a text snippet that validates the property values ​​exposed by the old specification and the new specification of the Network Messaging API. List items are hidden by default and are only shown if the corresponding attribute is supported.

The demo also detects whether the browser implements the old API specification (for Firefox) and whether the browser supports the Network Information API. In the first case, you will see the Old API Version Supported message, and in the second case, the API Not Supported message will be displayed.

The tests supported by the Network Information API are very simple and are as follows:

// Deal with vendor prefixes
var connection = window.navigator.connection    ||
                 window.navigator.mozConnection ||
                 null;
if (connection === null) {
   // API not supported :(
} else {
   // API supported! Let's start the fun :)
}
Copy after login

To detect whether the implemented version is an old specification, we can test whether the metered attribute exists as follows:

if ('metered' in connection) {
   // Old version
} else {
   // New version
}
Copy after login

Once we have tested support for the Network Information API and determined the version of the specification supported by the browser, we can attach handlers to the correct events. Within the handler, we update the text of the corresponding list item, such as type for the new API specification.

You can find the full code for the demo below and you can use it if you prefer.

<!DOCTYPE html>
<html>
   <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
      <meta name="author" content="Aurelio De Rosa">
      <title>Network Information API Demo by Aurelio De Rosa</title>
      <style>
         *
         {
            -webkit-box-sizing: border-box;
            -moz-box-sizing: border-box;
            box-sizing: border-box;
         }

         body
         {
            max-width: 500px;
            margin: 2em auto;
            padding: 0 0.5em;
            font-size: 20px;
         }

         h1
         {
            text-align: center;
         }

         .api-support
         {
            display: block;
         }

         .hidden
         {
            display: none;
         }

         .value
         {
            font-weight: bold;
         }

         .author
         {
            display: block;
            margin-top: 1em;
         }
      </style>
   </head>
   <body>
      <h1>Network Information API</h1>

      <span id="ni-unsupported" class="api-support hidden">API not supported</span>
      <span id="nio-supported" class="api-support hidden">Old API version supported</span>

      <ul>
         <li class="new-api hidden">
            The connection type is <span id="t-value" class="value">undefined</span>.
         </li>
         <li class="old-api hidden">
            The connection bandwidth is <span id="b-value" class="value">undefined</span>.
         </li>
         <li class="old-api hidden">
            The connection is <span id="m-value" class="value">undefined</span>.
         </li>
      </ul>

      <small class="author">
         Demo created by <a href="http://www.audero.it">Aurelio De Rosa</a>
         (<a href="https://twitter.com/AurelioDeRosa">@AurelioDeRosa</a>).<br />
         This demo is part of the <a href="https://github.com/AurelioDeRosa/HTML5-API-demos">HTML5 API demos repository</a>.
      </small>

      <script>
         var connection = window.navigator.connection    ||
                          window.navigator.mozConnection ||
                          null;
         if (connection === null) {
            document.getElementById('ni-unsupported').classList.remove('hidden');
         } else if ('metered' in connection) {
            document.getElementById('nio-supported').classList.remove('hidden');
            [].slice.call(document.getElementsByClassName('old-api')).forEach(function(element) {
               element.classList.remove('hidden');
            });

            var bandwidthValue = document.getElementById('b-value');
            var meteredValue = document.getElementById('m-value');

            connection.addEventListener('change', function (event) {
               bandwidthValue.innerHTML = connection.bandwidth;
               meteredValue.innerHTML = (connection.metered ? '' : 'not ') + 'metered';
            });
            connection.dispatchEvent(new Event('change'));
         } else {
            var typeValue = document.getElementById('t-value');
            [].slice.call(document.getElementsByClassName('new-api')).forEach(function(element) {
               element.classList.remove('hidden');
            });

            connection.addEventListener('typechange', function (event) {
               typeValue.innerHTML = connection.type;
            });
            connection.dispatchEvent(new Event('typechange'));
         }
      </script>
   </body>
</html>
Copy after login

in conclusion

In this article, I introduced you to the Network Information API. In the first part of this article, we discussed what an API is and what it can do for us. We also learned what properties and events the Network Information API exposes. As I mentioned in Browser Support, the API is currently poorly supported, partly due to some changes in the API specification.

The Network Information API is very simple to use, and once more browsers support it, there's no reason not to take advantage of the information it provides. What do you think of this API? Will you use it when more browsers support it?

The above is the detailed content of HTML5: Explore the Web Information API. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!