Last Updated: February 25, 2016
·
1.433K
· igama

Quick support for WebP - client side

There are various solutions to support WebP, server side (nginx/apache), JS rendering of the WebP, or using JS to select which image to select. I'm going to talk about the latest.

Modernizr allows to detect if the Browser supports WebP. This can be done with

Modernizr.webp

To use it, you need to get Modernizr with WebP support from Modernizer.com (Remember to enable img-webp from Non-Core section)

For example, if the main source of traffic you have is Chrome, maybe you can specify that by default your images will be WebP, and if the browser doesn't support them, then fallback to the alternative. The following JS would allow that:

/* Default images format : webp
 * If browser supports webp, will load .webp, else load something else.
 * 
 * <img src="/images/email.png"> - Directly specify image
 * <img data-src="/images/email.png" src="/images/example.webp"> - Default is webp, 
 *   if browser does not support, load data-src
 *
 */

window.onload  = function () {
  var i, images, supportWebp;

  // Can I support webp?
  supportWebp = Modernizr.webp;

  if (!supportWebp) {
    images = document.getElementsByTagName('img');
    for(var i = 0, len = images.length; i < len; i++) {
      if (images[i].hasAttribute('data-src')) {
        images[i].src = images[i].getAttribute('data-src');
      }
    }
  };

};

The main issue with this solution: If your browser doesn't support webp, it will start fetching the webp version before the JS changes the src to the alternative image.

As an alternative, you can contain 2 data attributes data-wepb and data-src:

//<img data-webp="/images/example.webp data-src="/images/email.png">

for(var i = 0, len = images.length; i < len; i++) {
    if (images[i].hasAttribute('data-webp') && supportWebp ) {
      images[i].src = images[i].getAttribute('data-webp');
    }  
    else if (images[i].hasAttribute('data-src')) {
      images[i].src = images[i].getAttribute('data-src');
    }
  }

With this solution, the browser will only start downloading images after the page finished loading.