Network Information API in HTML5

Introduction

 
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 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.
 
Example
  1. var video = document.getElementById("intro-video");  
  2. if (connection && !connection.metered && connection.bandwidth > 2) {  
  3.    video.src = "/videos/intro-video_hd.mp4"// load high-definitation video  
  4. }  
  5. else {  
  6.    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.
 
Example
  1. // Network Information object  
  2. var connection = navigator.connection || navigator.mozConnection || navigator.webkitConnection;  
  3. // initialize  
  4. if (connection) {   
  5.    connection.addEventListener("change", BandwidthChange);   
  6.    BandwidthChange();  

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