AngularJs detecting webP support

WebP is a new image format introduced by Google, what makes is special is the amount of transfer data you save as webP images are 26% smaller then a normal Jpg image.You can read more about webP on google developers.

Live example on plunker

WebP Support

WebP is natively supported by Chrome, Opera 11.10 and Android Android Ice Cream Sandwich or later.

It becomes really hard to work with an image format which is not globally supported by all the browser. And is even harder to leave the luxury provided by WebP as it reduce an image size by 26% , resulting in less data transfer and better user experience.

Below code will help you in setting up a bridge to detect whether user browser support WebP or not and on the basis on that you can make decision on which image format to show.

Angular service to detect browser support

// booting angular app
var app = angular.module('angularApp',[]);

// angular service to check webP support

app.factory('webPService',function($q){  
        return{
            isWebP:function(){
                var deferred = $q.defer();
                var hasWebP = false;
                var img = new Image();
                img.onload = function() {
                    hasWebP = !!(img.height > 0 && img.width > 0);
                    deferred.resolve(hasWebP);
                };
                img.onerror = function() {
                    hasWebP = false;
                    deferred.reject(hasWebP);
                };
                img.src = 'data:image/webp;base64,UklGRjIAAABXRUJQVlA4ICYAAACyAgCdASoCAAEALmk0mk0iIiIiIgBoSygABc6zbAAA/v56QAAAAA==';
                return deferred.promise;
            }
        }
    });

What we are doing is loading an inline image just ( 2Kb ) and checking whether it has been loaded successfully or not.
We have made use of Angular $q module to return a promise, helping us to wait for service to respond.

Using service

You can use the above service anywhere in your controllers or directives using DI. I will be demonstrating it's use with a controller.

app.controller('homeCtrl',function($scope,webPService){  
     var webPSupport = webPService.isWebP();
     $scope.name = '';
     webPSupport.then(function(){
        $scope.name = 'Webp is supported';
      },function(){
        $scope.name = 'Webp is not supported';
      })
});