Network Information API Polyfill

One of the many new HTML5 APIs slowly being implemented by browsers is the Network Information API[2]. It exposes information about the type of network that the connecting device is using. In theory, this allows developers to optimize content around the connection speed of the user. However, as with most HTML5 APIs it is supported only by some browsers with/without prefixes, and has a legacy implementation, so a polyfill is useful when working with the API.

How do it…

The API is located at window.navigator.connection. It has a type property and an ontypechange event. Here is a polyfill I created, based on work by Aurelio De Rosa[1]:

(function() {
  var oConnection = navigator.connection || navigator.mozConnection || navigator.webkitConnection;
  var sType;
  var aCallbacks = [];

  // Obviously this is not accurate.
  function fnGuessType(iBandwidth) {
    if (iBandwidth > 1) {
      return 'ethernet';
    } else if (iBandwidth > .5) {
      return 'wifi';
    } else if (iBandwidth === 0) {
      return 'none';
    } else {
      return 'cellular';

  // Simple function to iterate over the callbacks.
  function fnCallbackIter(fn) {
    for (var i = aCallbacks.length - 1; 0 <= i; i--) {

  if (oConnection) {
    // API is available.
    if ('metered' in oConnection) {
      // Legacy API, create obfuscation polyfill.
      sType = fnGuessType(oConnection.bandwidth);

      // If the bandwidth changes drastically, execute callbacks.
      oConnection.addEventListener('change', function(event) {
        var sNewType = fnGuessType(oConnection.bandwidth);
        if (sType !== sNewType) {
          sType = sNewType;
          fnCallbackIter(function(fnCallback) {
  , event);

      navigator.connection = {
        addEventListener: function(sName, fnCallback) {
          var bFoundCallback = false;
          if (sName === 'typechange') {
            // Assert the callback doesn't exist before appending.
            fnCallbackIter(function(fnCallbackInner) {
              if (fnCallback === fnCallbackInner) {
                bFoundCallback = true;
            if (!bFoundCallback) {
          } else {
            // Some other event... pass through.
            oConnection.addEventListener.apply(this, arguments);
        removeEventListener: function(sName, fnCallback) {
          var aNewCallbacks = [];
          if (sName === 'typechange') {
            if (fnCallback) {
              // Create a new list of callbacks without the provided one.
              aNewCallbacks = [];
              fnCallbackIter(function(fnCallbackInner) {
                if (fnCallback !== fnCallbackInner) {
            aCallbacks = aNewCallbacks;
          } else {
            // Some other event... pass through.
            oConnection.addEventListener.apply(this, arguments);
        type: 'unknown'

    // Don’t change the connection object.
  } else {
    // API doesn't exist, create empty polyfill.
    navigator.connection = {
      addEventListener: function() {},
      removeEventListener: function() {},
      type: 'unknown'

How it works…

The polyfill has three paths: leave the browser implemented connection API alone, replace it with an empty polyfill object, or replace it with a polyfill to mask the legacy version. The first two need no explanation, except the possible type values are:

  • bluetooth
  • cellular – connected via mobile network (edge, 3G, 4G, etc.)
  • ethernet
  • none – no internet connection
  • wifi
  • other – not unknown, but not one of the above either
  • unknown – couldn’t determine connection type

The legacy API exposes the metered (boolean indicating the connection is metered) and bandwidth (rate in MB/s) properties instead of type. While this is probably more meaningful information, it was difficult to implement and has been replaced with just the type property.

The majority of the legacy polyfill is to implement versions of addEventListener and removeEventListener to mask the DOM event handler functions with custom ones, so that the typechange event can be used instead of the legacy change event. Additionally, the code estimates the type based on the bandwidth value. Obviously, this is very inaccurate, but I believe it returns values in the spirit of how you might use type in a real project.

Whilst this is a fun experiment, use it in production at your own risk. I definitely had some weird data. For example my laptop using the legacy polyfill while connected via wifi, always reported the value Infinite for the bandwidth, so the polyfill type was set to ethernet. However, I do have more than 10MB/s download speeds, so perhaps I exceeded FireFox’s maximum bandwidth value. I was not able to test the polyfill on my mobile devices as none of my devices had the legacy version.

I think the best use for the Network Information API would be to load a page with the lowest viable resolution assets, and dynamically insert larger, more detailed assets if the type is
wifi or ethernet.

There’s more…

There is more value in estimating bandwidth than there is from knowing the type, as you can be connected using wifi to another cellphone and shouldn’t assume that wifi means a fast connection. It might be more useful to polyfill the current API with the legacy API by estimating the bandwidth. This could be achieved by timing the download of several small files and calculating a rough bandwidth.


  1. HTML5: Network Information API
  2. MDN: Network Information API
  3. Chrome Canary has an experimental implementation of NetInfo API

Using jQuery Mobile With Django HTML5 Boilerplate

In the last article, I introduced the Django HTML5 Boilerplate package, which incorporates HTML5 Boilerplate into an easy to use Django package. Today’s article will take that one step further by showing how to use DH5BP to create a base template for your HTML 5 mobile app. We will be using jQuery mobile and the jQuery Widget for Showing Add To Home Message on iOS.

Getting ready

Install Django ...

Django HTML5 Boilerplate

I am a big fan of the HTML 5 Boilerplate project, and in that past, I have made some half-hearted attempts to incorporate it into a reusable Django module. I think the problem with my attempts and the other attempts that I have found recently on the web is that nobody automated the process of converting H5BP into a django module, so each time H5BP is updated (which happens frequently), somebody has to ...

jQuery Widget for Showing Add To Home Message on iOS

I recently wrote an article discussing Making HTML5 Apps Appear Native on iOS where I mentioned building a widget for telling the users to add your application to the home screen. This article introduces a simple jQuery plugin that can be used to show the Add to Home message on an iOS device. It is fully customizable, but looks good right out of the box.

Getting ready

Download the plugin at the

Rotating Multi-State Button

One of the designers at Ariba, recently came up with a design that needed a tri-state button to govern toggling some content. We came up with an interesting solution where the button has three colors on the outside, with the bottom color governing the content being shown. I am not sure if the widget will survive a usability study, but I put together a proof of concept using HTML 5 technologies and wanted to share ...

Cross Browser and Legacy Supported RequestFrameAnimation

There is an awesome new feature in HTML 5, window.requestAnimationFrame, which tells the browser that you wish to perform an animation and requests that the browser schedule a repaint of the window for the next animation frame1. This allows you to do animations more efficiently and without using setInterval or series of setTimeout function(s). I have created a Demo that attempts to use the browser’s requestAnimationFrame side-by-side with the legacy polyfill executing.

Article ...

Legacy Support for HTML 5 Forms

As discussed in the article, HTML 5 Feature Detection Using Modernizr, HTML 5 contains many new input types and attributes. While, most new browsers support them (although often imperfectly), the majority of people still use browsers that do not. However, we can use JavaScript to provided legacy support for the new HTML 5 input attributes and types in browsers that lack support. Toadys article introduces a widget for the YUI 3 gallery, that emulates ...

HTML 5 Feature Detection Using Modernizr

HTML 5 is probably the most exciting improvement to come to the web, since the popularization of AJAX. However, as shown by last weeks article (HTML 5 Forms), only the most cutting edge browsers support many of the new HTML 5 features. To progressively enhance a site for HTML 5 enabled browsers, developers need a way to detect if the browser supports a desired HTML 5 feature. Enter Modernizr by Faruk Ates ...

HTML 5 Forms

HTML 5 is quickly gaining in popularity and is appearing more frequently across the web. While you may hear about the awesomeness of HTML5s new JavaScript and CSS features, the actual HTML improves are often missed. Lets look at the thirteen new form field types and some of the more useful new form field attributes. Not all browsers support HTML 5 forms yet, and those that dont will render the new input types as text ...

Introducing Web Workers

The HTML 5 specification introduces a new technology called Web Workers, allowing developers to spawn new threads for processing JavaScript code. This is a major improvement from the current state of the web, as it allows JavaScript code to execute outside of the UI thread, so your application is still responsive during long-running scripts. However, due to the nature of Web Workers there are restrictions to what they can and cant do, and how to ...