Knowing the current strength of a device’s Internet connection is extremely useful; you may want to serve lower-resolution images to devices with low bandwidth or stream different video qualities to users depending on their connection. Likewise, you may want to hold off on the background processes if the user has a limited or metered tariff.
The Network Information API is composed of two attributes on the connection object: bandwidth, which is a figure representing the estimated bandwidth in Megabytes (MBps) of the current connection (0 if the device is offline, infinity if the result is unknown); and metered, a Boolean that returns true if the connection is metered (such as on pay-as-you-go tariffs).
The following code shows a function that uses both attributes: bandwidth to return the current connection’s bandwidth and metered to add an extra message to the status if the connection is limited.
var status,
connection = navigator.connection,
showStatus = function () {
status = connection.bandwidth + ' MB/s';
if (connection.metered) {
status += ' (metered)';
}
alert(status);
};
showStatus();
Network Information also has an event handler, change, on the connection object, which fires whenever the connection status changes; with this, you can easily add an extra call to the function when necessary:
connection.addEventListener('change', showStatus, false);
You can see both at work in the file network.html—try connecting or disconnecting your Wi-Fi service to see the change event fire.