Middle
How to implement support for WebP format with fallback for other image formats?
sobes.tech AI
Answer from AI
The most common way is to use the <picture> element or CSS with the image-set() function.
<picture> element:
<picture>
<source srcset="image.webp" type="image/webp">
<img src="image.jpg" alt="Image description">
</picture>
- The browser first checks for support of
image/webp. If supported, it loads the.webp. - If not supported, it loads the image from the
srcattribute of the<img>tag.
CSS with image-set():
.element {
background-image: url("image.jpg"); /* Fallback */
background-image: image-set(
url("image.webp") type("image/webp"),
url("image.jpg") type("image/jpeg")
);
}
- Browsers supporting
image-set()andimage/webpwill load WebP. - Otherwise, the
background-imagefallback is used.
CSS with @supports:
.element {
background-image: url("image.jpg"); /* Fallback */
}
@supports (image-set(url("x") type("image/webp"), url("x") type("image/jpeg"))) {
.element {
background-image: image-set(
url("image.webp") type("image/webp"),
url("image.jpg") type("image/jpeg")
);
}
}
- More explicit use of
@supportsto check support forimage-set()andimage/webp.
JavaScript support detection:
You can use JavaScript to check WebP support and dynamically change src or use other classes, but this is considered less optimal as it delays content rendering and requires additional requests.
// Example of WebP support check (simplified)
function checkWebp(callback) {
const webp = new Image();
webp.onload = webp.onerror = function() {
callback(webp.height === 2);
};
webp.src = 'data:image/webp;base64,UklGRjoAAABXRUJQVlA4ICgAAAAwAQCdASoCAAIALmk0mk0iIiIiIgBoDvgbAQAAAP0ybQbAAADp+lWu/rXcAAAAA';
}
checkWebp(function(supported) {
if (supported) {
// Use WebP
} else {
// Use fallback
}
});