Recently, I have been doing product performance optimization, one of which is image optimization. Webp is commonly used to replace PNG, JPG and other formats. Note Mobile browsers of different versions need to be checked to see whether the webP format is supported.

  1. Using the canvas API
function isSupportWebp(){
  const ele = window.document.createElement('canvas')
  if(!!!!! (ele.getContext && ele.getContext('2d'))) {
    return ele.toDataURL('image/webp').indexOf('webp') > -1
  }
  // If canvas is not supported, webP is definitely not supported
  return false
  }
Copy the code
  1. Google’s official recommended method

// check_webp_feature:
// 'feature' can be one of 'lossy', 'lossless', 'alpha' or 'animation'.
// 'callback(feature, isSupported)' will be passed back the detection result (in an asynchronous way!)
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
check_webp_feature('lossy'.function (feature, isSupported) {
    if (isSupported) {
        // webp is supported, 
        // you can cache the result here if you want}});Copy the code

This method first loads a WebP image (a Base64 string). If width and height are available, webP is supported, otherwise it is not.

3. The server checks the accept value of the Request Headers in the HTTP Request. If image/webp exists, the server returns a webP image; otherwise, the server returns a PNG image.

  1. Html5’s Picture TAB will automatically select the most matched resource to load. If webP is supported, webP is loaded first, otherwise resources in the SRC path within the IMG tag are loaded.
<picture>
  <source srcset="/path/to/image.webp" type="image/webp">
  <img src="/path/to/image.jpg" alt="insert alt text here">
</picture>
Copy the code