Network Information API in HTML5

Designing a responsive Web Site is now easy with the available frameworks like Bootstrap. But serving the right resources like images, video and so on for a responsive site accessed in the various internet speeds and in the various devices is difficult nowadays, especially on sites that provide games.

It is now possible to serve the right resources for the right site that has the specific internet speed. Yes, now HTML5 provides a JavaScript API called Network Information API by which we can serve the right resources to the site.

Supporting Browsers

As of now Chrome and Firefox support the Network Information API. The API has two main properties called bandwidth and metered and an event called onchange.

How to use Network Information API

We can access the Network Information API from Navigator's connection object as in the following:

var connection = navigator.connection || navigator.mozConnection || navigator.webkitConnection;

The connection object has two properties as explained above.

bandwidth is of type Double that represents an estimation of the current bandwidth in MB/s (Megabytes per second). The value will be zero if the user is offline and Infinity if it cannot be determined.

metered a Boolean property, a true value indicates that the user's connection is subject to limitation and bandwidth usage should be limited where possible.


var video = document.getElementById("intro-video");
if (connection && !connection.metered && connection.bandwidth > 2) {
   video.src = "/videos/intro-video_hd.mp4"; // load high-definitation video
else {
   video.src = "/videos/intro-video_normal.mp4";

Detecting Connection Changes

The Network Information API provides an event called onchange, by which we can check the status of the internet speed.


// Network Information object
var connection = navigator.connection || navigator.mozConnection || navigator.webkitConnection;
// initialize
if (connection) {
   connection.addEventListener("change", BandwidthChange);

In the bandwidthChange function we add the functionality to change the resources depending on the connection status.

Happy Coding.

Up Next
    Ebook Download
    View all
    View all