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:
html
Structure not moving, for not supportedpicture
Browser,picture
Tags don’t parse,img
withpicture
At the same level. socss
Set up goodpicture
Will not be valid. So this way is suitableimg
Where the style structure is simple. Also due to unsupportedpicture
, therefore,source
In the2x/3x
You 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
- 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
- The introduction of
JS polyfill
The scriptpicturefillTo support thepicture
Native functionality, including the responsive support mentioned above (media/2x/3x
Etc.)
<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-…