The benefits of using WebP in your project won’t be covered here, as detailed in the Chrome Performance Optimization Guide. The following is mainly about how to land in the project.

picture

Use the picture tag, which is a new tag in HTML5. For browser support, see Caniuse

The srcset of the source tag is used to mark the image link. The type of the image is the type of the image. The img element is loaded from the first source.

Lazy-load is also available when the IMG element is at the bottom, and its own class is not affected.

<picture>
    <source srcset="teal.png! 750.webp" type="image/webp">
    <img src="teal.png" data-original="" class="" />
</picture>
Copy the code

There are two solutions for dealing with unsupported browsers:

  1. htmlStructure not moving, for not supportedpictureBrowser,pictureTags don’t parse,imgwithpictureAt the same level. socssSet up goodpictureWill not be valid. So this way is suitableimgWhere the style structure is simple. Also due to unsupportedpicture, therefore,sourceIn the2x/3xYou don’t have to use the response formula. It’s just simplesrc fallback.

“Picture” is not parsed correctly:

<picture>
<source srcset="teal.png! 750.webp" type="image/webp">
<img src="teal.png" />
<picture>
Copy the code
  1. Check whether the browser supports it at runtime, and then replace the image format with JS
/** * check whether user-agent supports webp images * @return thenable function */
const checkWebp = function () {
    return new Promise(((resolve) = > {
        const img = new Image()
        const dataUri = 'data:image/webp; base64,UklGRiIAAABXRUJQVlA4IBYAAAAwAQCdASoBAAEADsD+JaQAA3AAAAAA'
        img.onload = function () {
            const result = (img.width > 0) && (img.height > 0)
            resolve(result)
        }
        img.onerror = function () {
            resolve(false)
        }
        img.src = dataUri
    }))
}
Copy the code
  1. The introduction ofJS polyfillThe scriptpicturefillTo support thepictureNative functionality, including the responsive support mentioned above (media/2x/3xEtc.)
<picture>
    <source srcset="teal.png! 750.webp" type="image/webp" media="(min-width: 768px)">
    <source srcset="teal.png! 750.webp 2x" type="image/webp">
    <img src="teal.png" />
</picture>
Copy the code

Read more:

Css-tricks.com/using-webp-…