How to Use the Network Information API to Improve Responsive Websites

Share this article

Responsive Web Design has revolutionized the web. A single site can adapt its layout when viewed on a range of differing devices and screens. All that’s required is a few media queries to detect the screen size and load alternative styles or stylesheets. However, using the screen size to detect browser capabilities is akin to judging a car’s speed by looking at its radio. Modern smartphones and tablets have increasingly large resolutions and will happily show a typical desktop view. If that view adds numerous fonts, images or other assets, the mobile user may receive a degraded — and expensive — experience because they’re on a slower or metered connection.

The Network Information API

The Network Information API may help. It indicates whether the user is on a metered connection, such as pay-as-you-go, and provides an estimate of bandwidth. Using this information it’s possible to conditionally load images, videos, fonts and other resources. At a basic level, you could override a media query to ensure the mobile layout is retained on a limited network.

Browser Support

Despite the Network Information API draft specification being released in 2011, only Firefox and Chrome offer experimental support at this time. Until we have vendor consensus, the API is subject to change:
  • assessing bandwidth is difficult. It may change frequently as you move around or switch between mobile and wi-fi networks. Network capacity may be good, but it doesn’t follow that a connection to a specific server will be. Keeping the bandwidth estimate up-to-date may also be processor and network-intensive.
  • how can the device know whether your connection is metered? Even fast wi-fi may have ludicrously extortionate costs at some hotels and airports I could mention. One option would be for the device to prompt you when a new connection is made.
Fortunately, we can use object detection to detect for the presence of the API.

API Basics

The Network Information API object is returned by navigator.connection. To ensure cross-browser compatibility, we need:
var connection = navigator.connection || navigator.mozConnection || navigator.webkitConnection;
You may want to add navigator.msConnection to that list, although IE normally implements non-prefixed APIs. Our connection object provides two read-only properties:
  • bandwidth — a double representing 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. Note most network providers quote values in Megabits per second and a typical busy mobile 3G connection will be around 400Mbps ~= 400,000 bits/s ~= 50Kb/s ~= 0.05MB/s.
  • metered — a Boolean which, when true, means the user’s connection is subject to limitation and bandwidth usage should be limited where possible.
For example:
if (connection && !connection.metered && connection.bandwidth > 2) {
// load high-resolution image
var img = document.getElementById("kitten");

img.src = "/images/kitten_hd.jpg";
}
Finally, we can execute a change event handler when the connection status changes, e.g.
// default bandwidth
var highBandwidth = false;

// bandwidth change handler
function BandwidthChange() {
highBandwidth = (!connection.metered && connection.bandwidth > 2);
console.log(
"switching to " +
(highBandwidth ? "high" : "low") +
" bandwidth mode"
);
}

// Network Information object
var connection = navigator.connection || navigator.mozConnection || navigator.webkitConnection;

// initialize
if (connection) {
connection.addEventListener("change", BandwidthChange);
BandwidthChange();
}
In this code, the global highBandwidth variable will be set true when high bandwidth is available. Other code could react accordingly, e.g. when highBandwidth is false:
  1. high-resolution images are not loaded
  2. unnecessary fonts are not loaded
  3. Ajax polling is slowed down
  4. Ajax timeout parameters are increased
To make things a little easier, you could append a class to the body tag in the BandwidthChange
function, e.g.
// bandwidth change handler
function BandwidthChange() {
highBandwidth = (!connection.metered && connection.bandwidth > 2);

var body = document.body;

if (highBandwidth) {
body.classList.add("hibw");
}
else {
body.classList.remove("hibw");
}

console.log(
"switching to " +
(highBandwidth ? "high" : "low") +
" bandwidth mode"
);
}
This allows us to conditionally load items such as background images in CSS, e.g.
/* low bandwidth plain-color background */
#myelement
{
background-color: #ccc;
}

/* high bandwidth image background */
body.hibw #myelement
{
background: url(image.jpg) 0 0 no-repeat;
}
This condition can still be checked in desktop layouts loaded by media queries.

Should You Use the Network Information API?

At the time of writing, the Network Information API has little browser support and could change. That said, if you’re creating a website or application which must work on mobile devices, a little planning now could prevent your pages from reaching 1.7Mb. If the API changes, you’d simply need to update the BandwidthChange function and your site would react appropriately. I certainly think the Network Information API is worth consideration. Do you?

Frequently Asked Questions (FAQs) about Network Information API

What is the Network Information API and how does it work?

The Network Information API is a tool that provides information about the network connection a device is using to communicate with the web. It allows web applications to access the status of a device’s network type and speed, which can be used to optimize content delivery. For instance, if a user is on a slow network, a website could choose to send lower quality images to improve load times.

How can I use the Network Information API to improve my responsive website?

The Network Information API can be used to enhance the user experience on your responsive website. By detecting the user’s network conditions, you can adapt your website’s behavior accordingly. For example, if the user’s network is slow, you can reduce the amount of data you send, such as lower resolution images or less video content. This can significantly improve the loading speed and overall performance of your website.

Is the Network Information API supported by all browsers?

The Network Information API is not supported by all browsers. As of now, it is supported by Chrome, Opera, and Android browsers. It’s always a good idea to check the latest browser compatibility information on websites like “Can I use” before implementing any new APIs.

How can I implement the Network Information API in my web application?

Implementing the Network Information API involves using JavaScript to access the Network Information API’s properties and methods. You can use the navigator.connection or navigator.mozConnection properties to get a NetworkInformation object representing the user’s connection, and then use this object’s properties and event handlers to get information about the connection and react to changes in the connection.

What kind of information can I get from the Network Information API?

The Network Information API provides several properties that give information about the user’s network connection. These include downlink, effectiveType, and rtt, which provide the bandwidth in megabits per second, the effective type of the connection, and the round-trip time in milliseconds, respectively.

Can the Network Information API be used to detect offline status?

Yes, the Network Information API can be used to detect if the user’s device is offline. The navigator.onLine property returns a Boolean value that indicates whether the user’s device is online or offline.

How reliable is the data from the Network Information API?

The data from the Network Information API is an estimate and may not be completely accurate. It’s based on recently observed network conditions and may not reflect the actual current network conditions. Therefore, it should be used as a guide rather than a definitive measure of network conditions.

Can the Network Information API be used with service workers?

Yes, the Network Information API can be used with service workers. This allows you to adapt the behavior of your service worker based on the user’s network conditions, such as caching more aggressively when the user is on a slow network.

What are the privacy implications of using the Network Information API?

The Network Information API can potentially be used to fingerprint users based on their network conditions. However, the API only provides coarse-grained information about the network, and this information is also available to native applications, so the additional privacy risk is minimal.

What are some use cases for the Network Information API?

The Network Information API can be used in a variety of ways to improve the user experience. For example, a video streaming site could use it to automatically select the appropriate video quality based on the user’s network speed. A news site could use it to decide whether to load high-resolution images or lower-quality ones. A web app could use it to warn users when they’re on a slow network and some features might not work optimally.

Craig BucklerCraig Buckler
View Author

Craig is a freelance UK web consultant who built his first page for IE2.0 in 1995. Since that time he's been advocating standards, accessibility, and best-practice HTML5 techniques. He's created enterprise specifications, websites and online applications for companies and organisations including the UK Parliament, the European Parliament, the Department of Energy & Climate Change, Microsoft, and more. He's written more than 1,000 articles for SitePoint and you can find him @craigbuckler.

apibandwidthHTML5 Tutorials & Articlesjavascript
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week