What is Webp?

Webp is an image format that supports lossy and lossless compression on the Web (and also supports dynamic images and transparency), which was released by Google in September 2010. The main purpose of this image format is to create smaller or better images than JPG, PNG and GIF. By March 2021, webP image support accounted for 93 percent of the world’s browsers.

Why use Webp?

Before answering this question, you need to define the context of the question. Webp, as its name suggests, is designed to optimize the size of existing image resources in web scenarios. It is not suitable for other scenarios, such as professional design fields, or even just wallpaper scenarios. (After all, Windows does not support preview webP format by default. MAC just gave it a preview). Why use WebP in a Web scenario? Compared with PNG or GIF, WebP is smaller in size. In Web scenarios, webP can save users’ network traffic, accelerate the opening of web pages, and improve user experience. The figure below is the comparison of the overall image resource size before and after using WebP images in the actual project (the left picture is before optimization, the right picture is after optimization)

👆 After using WebP, the overall transmission size of image resources is reduced from 2.6m to 1.0m. And the difference between the compressed image and the original image is also very small, you can see the effect of the image before and after compression through the following figure.

For a comparison of size and quality before and after compression, see the following links: Webp example (PNG to Webp)/Webp example (Animated Webp).

Browser support for Webp

According to Wikipedia, webP images will be supported by 93% of the world’s browsers as of March 2021, but for more detailed information on support, see: Can I Use Webp?

It can be seen that webP browsers in China account for 78.12% of the total. Internet Explorer does not support WebP at all in all browser versions, and Safari did not support webP until macOS 11 and later. Android mobile terminal support for WebP is very good, plus mobile terminal with the system browser feeling is not too much (especially after the mobile phone manufacturers magic changed the system), so basically there is no problem. On IOS, webP is not supported until IOS 14. It is worth noting that third-party browsers on IOS are based on the rendering engine of Safari browser, so any browser before IOS 14 should not support WebP. reference

How do I determine whether the current browser supports WebP?

There are several ways to determine whether a browser supports the WebP format:

1. HTTP request header

When the browser requests an image resource, the accept field in the request header indicates the image format it supports:

As you can see, in the Accept field, if the browser currently in use supports the WebP format, it will have the words image/webp, and the server can use this request header to decide whether to return the webP format image.

2. Load a WebP image with JS

In some scenarios, such as when the back end does not have dynamic WebP compression capability, or when oss is used, we need to determine whether the browser supports WebP in advance and then request the corresponding image resources, so the front end needs to determine the browser support capability. The easiest way to do this is to use the browser to load the resource (such as flAC lossless Audio with the Audio tag). If the browser can load the resource successfully, the corresponding onLoad event will be raised, and if the browser can load the resource successfully, the corresponding onLoad event will be raised. On this basis, it can dynamically load a 1px * 1px WebP image with JS without the user’s perception and determine whether the browser supports it by its loading condition. The code is as follows:

/ * * *@function
 * @return {Promise<boolean>}
 * @description Checks whether the current device supports' webP '. * /
export function checkIfWebpSupported () :Promise<boolean> {
    if (!window) {
        throw new Error('Non-browser environment');
    }
    
    const { Image } = window;

    if(! Image)return Promise.resolve(false); // WebP support cannot be determined

    return new Promise<boolean> (resolve= > {
        const image = new Image();
        image.onload = () = > {
            if (image.width === 1 && image.height === 1) {
                // The current browser supports WebP
                resolve(true);
            } else {
                resolve(false); }}; image.onerror =() = > {
            resolve(false);
        };
        image.src = "data:image/webp; base64,UklGRh4AAABXRUJQVlA4TBEAAAAvAAAAAAfQ//73v/+BiOh/AAA=";
    });
}
Copy the code

The above code returns a Promise by calling checkIfWebpSupported (). Then (isSupported => {}); The judgment result can be obtained in then.

3. Use Canvas to generate WebP

Canvas can convert the Canvas content to a Base64 encoded image resource string using the toDataURL() method, which takes two parameters, the first parameter is the type of image resource (image/ PNG by default), and the second parameter is the quality of the image resource. Webp-enabled browsers that call this method with type image/webp return the resource address with the word image/webp, while browsers that do not support Webp return image/ PNG. We can use this feature to determine whether the browser supports WebP:

/ * * *@function
 * @return {boolean}
 * @description Checks whether the current device supports' webP '. * /
 export function checkIfWebpSupported () :boolean {
     if (!document) {
        throw new Error('Non-browser environment');
    }
    
    if (!document.createElement) return false; 
    
    return document.createElement('canvas').toDataURL('image/webp').indexOf('image/webp') > -1;
 }
Copy the code

conclusion

Webp has the characteristics of high compression rate and no great visual difference between image quality and original image, which makes it very suitable for web pages with many pictures but not very high requirements for picture quality. In practice, we can use the above methods to judge the support degree of webP in the browser, and replace the website image resources with WebP format. For the browser that does not support webP, we request the original image as fallback to ensure the normal display of the page. Of course, the judgment on WebP support only needs to be made once. We can cache the judgment results after we get them for the first time, and then take the results from the cache where we need to ensure webP support.