Detect if browser supports base64 dataURI using JavaScript

A long time ago Flickr have introduced base64 dataURI images in its pages. It brings a lot of benefits for users and web servers but at the time the most of the browsers was not supporting this schema.

For the ones that does not konw what base64 data URI is, just mind to something that is written using 6 bits (a nibble and half) instead of 8 bits and using only the ASCII printable characters to encode the contents.

An example of what I’m meaning is the text “Hello World!” that in base64 encoding would be “SGVsbG8gV29ybGQh“.

Let’s suppose you want to know if the user’s browser supports base64 data URI to reserve hime some special features and implement alternatives to those that does not. The question is: how to know that?

There is a simple (I think the simplest) way to make this feature detection and is:

  1. create a new script tagthrough javascript,
  2. set the source with a base64 dataURI,
  3. and put it somewhere in your page

However the base64 dataURI must be composed with a specific content.

The following code can save you a lot of time:

window.supportsBase64 = false;

var body = (document.querySelector) ? 
    document.querySelector('body') : 
    document.getElementByName('body')[0];

var script = document.createElement('script');
script.src = 'data:text/javascript;charset=utf-8;base64,' + btoa("window.supportsBase64=true;");
script.defer = true;
body.appendChild(script);

script.onload = function(){
    if(window.supportsBase64){
        body.className += ((body.className !== '')?' ':'') + 'has-b64';
    }else{
        alert('Sorry your browser does not support base64 dataURI');
    }
}

Code analisys

  1. First of all we define a window attribute ( supportsBase64) and getting the body element.
  2. And the next 4 lines needs to create a script tag which src attribute is a dataURI that will change the window.supportsBase64 state variable from false to true…. but it’s true only if the browser supports the base64 dataURI.
  3. In the end we make sure to append a body class to allow the CSS to know if the browser supports base64.

The most important row in the above source code is the following one:

script.src = 'data:text/javascript;charset=utf-8;base64,' + btoa("window.supportsBase64=true;");

For further details on the meaining of the above string please refer to my previous article and to the btoa method documentation on Mozilla Developer Network.

The following fiddle shows you a working demo.

Easy… as 1,2, 3! Are you agree?


Commenti

Una risposta a “Detect if browser supports base64 dataURI using JavaScript”

  1. I read this paragraph completely about the comparison of latest and earlier
    technologies, it’s remarkable article.