As we all know, WebP is the WebP image format launched by Google. It is a kind of image file format that supports lossy compression and lossless compression. According to Google’s test, the same image, WebP image can save a lot of volume than PNG and JPG image, but its compatibility is not very good. As follows:

So we need to do some compatibility, so how can we tell if the browser supports WebP? There are several ways to do this.

Methods a

Use canvas’s toDataURL to judge

ToDataURL method in MDN is explained as follows:

HTMLCanvasElement. ToDataURL () method returns a data URI contains pictures show. You can use the type parameter, which is PNG by default. The image resolution is 96dpi.

  • If the height or width of the canvas is 0, the string “data:,” is returned.
  • If the type passed is not “image/ PNG”, but the value returned begins with “data:image/ PNG”, the type passed is not supported.
  • Chrome supports the image/ Webp type.

The toDataURL method transforms the image into a DOMString containing dataURI, which can be judged by the image type value before base64 encoding is Image/webP.

For example, in Google Chrome use the toDataURL method to convert image/webp:

Convert to image/webp using the toDataURL method in Safari:

It can be found that the image type obtained by toDataURL in a browser that does not support WebP is not WebP, so we can judge by this.

Implementation method:

var isSupportWebp = function () {
  try {
    return document.createElement('canvas').toDataURL('image/webp'.0.5).indexOf('data:image/webp') = = =0;
  } catch(err) {
    return false;
  }
}

isSupportWebp()
Copy the code

Method 2

The server determines whether the browser supports WebP based on the request header information

A Google Chrome image header request looks like this:

Internet Explorer requests image headers like this:

If the Request Headers contains Accept, the server can determine whether the Accept contains image/webp.

Methods three

Judge by loading a WebP image

const supportsWebp = ({ createImageBitmap, Image }) = > {
  if(! createImageBitmap || ! Image)return Promise.resolve(false);

  return new Promise(resolve= > {
      const image = new Image();
      image.onload = (a)= > {
          createImageBitmap(image)
              .then((a)= > {
                  resolve(true);
              })
              .catch((a)= > {
                  resolve(false);
              });
      };
      image.onerror = (a)= > {
          resolve(false);
      };
      image.src = 'data:image/webp; base64,UklGRh4AAABXRUJQVlA4TBEAAAAvAAAAAAfQ//73v/+BiOh/AAA=';
  });
};

const webpIsSupported = (a)= > {
  let memo = null;
  return (a)= > {
      if(! memo) { memo = supportsWebp(window);
      }
      return memo;
  };
};

webpIsSupported()().then(res= > {
    console.log("Do you support WebP?", res)
}).catch(err= > {
    console.log(err)
})
Copy the code

This method loads a 1×1 white square background to test whether the browser supports WebP.

Test the code at Google:

Test code in Firefox:

Test code in Safari:

If the width and height of the image can be obtained, it indicates that WebP is supported. Otherwise, it does not support WebP.

function check_webp_feature(feature, callback) {
    var kTestImages = {
        lossy: "UklGRiIAAABXRUJQVlA4IBYAAAAwAQCdASoBAAEADsD+JaQAA3AAAAAA".lossless: "UklGRhoAAABXRUJQVlA4TA0AAAAvAAAAEAcQERGIiP4HAA==".alpha: "UklGRkoAAABXRUJQVlA4WAoAAAAQAAAAAAAAAAAAQUxQSAwAAAARBxAR/Q9ERP8DAABWUDggGAAAABQBAJ0BKgEAAQAAAP4AAA3AAP7mtQAAAA==".animation: "UklGRlIAAABXRUJQVlA4WAoAAAASAAAAAAAAAAAAQU5JTQYAAAD/////AABBTk1GJgAAAAAAAAAAAAAAAAAAAGQAAABWUDhMDQAAAC8AAAAQBxAREYiI/gc A"
    };
    var img = new Image();
    img.onload = function () {
        var result = (img.width > 0) && (img.height > 0);
        callback(feature, result);
    };
    img.onerror = function () {
        callback(feature, false);
    };
    img.src = "data:image/webp; base64," + kTestImages[feature];
}
Copy the code

reference

  • HTMLCanvasElement.toDataURL()
  • Detect WEBP Support with JavaScript
  • Explore WebP a few things