How to use the Network Information API

All the websites we build should be responsive; not just to browser speed, but to network condition.

In this article I’ll introduce the Network Information API, that helps us detect a device’s current bandwidth and allows us to modify our site if the speed is slower than we need.

Browser support

We usually can’t expect support for experimental APIs and in this case, the only two browsers that support it are Firefox and Chrome. In both cases, you need browser prefixes.

How to use the Network Information API

As usual, the first thing to do is test for support in the user’s browser, like so:

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

After this all we need is to test for the connection value:

if(connection) {
 // Supported

Now, we’ll set up a switch statement to determine if the user is on a high bandwidth connection like Wifi, or a low bandwidth connection like 3G.

We’ll use the switch to populate two variables that we’ll later use to modify our content:

    switch(connection.type) {
        case connection.CELL_3G:
            connectionBand = 'Medium Bandwidth';
            bodyClass = 'medium-bandwidth';
        case connection.CELL_2G:
            connectionBand = 'Low Bandwidth';
            bodyClass = 'low-bandwidth';
            connectionBand = 'High Bandwidth';
            bodyClass = 'high-bandwidth';

As you can see we ran through the possible types of connection and set a readable name and a class name for it, we also set one as default that will be used when the user is using ethernet, Wifi or unknown.

After this is done we can do what we please with the variables, first lets add the appropriate class to the body:


I also want the user to see the bandwidth type so I will append the readable name version to a div so that the user can see the Bandwidth speed:

$('.band').append('Bandwidth: ' + connectionBand);

Another value I want the user to have is the actual speed of the internet connection and for that we just need to use connection.bandwidth:

$('.speed').append('Speed: ' + connection.bandwidth);

If the user is offline this will return the value 0, if the API can not return a number it will return infinity but if it is able to get the value it will be returned in Megabits per second.

Now that we have all of this information and even a special class on the body we can adjust our website to the speed of the internet and set the minimal amount of CSS, reduce the images or anything we please when the speed is less than optimum.

You can see this working in the pen I made.

Sara Vieira is a freelance Web Designer and Developer with a passion for HTML5/CSS3 and jQuery. You can follow her on twitter or check out her website. More articles by Sara Vieira
Home CSS Deals DesignBombs HTML HTML5 JavaScript jQuery Miscellaneous Mobile MySQL News PHP Resources Security Snippet Tools Tutorial Web Development Web Services WordPress