WebP is the best image solution at Web. It is smaller than JPEG/PNG with the same quality because of VP8.
WebP lossless images are 26% smaller in size compared to PNGs. WebP lossy images are 25–34% smaller than comparable JPEG images at equivalent SSIM quality index
En. the first method I could use is checking the user agent. You can use a UA whitelist to detect which browser uses the correct image format.
And it also supports SSR, if you won’t handle the logic in node.js server.
The second one? We can load a WebP image and return a promise.
function checkWebPSupport) {
return new Promise((resolve, reject) => {
var img = new Image();
img.onload = function() { resolve(); };
img.onerror = function() { reject(); };
img.src = 'http://www.gstatic.com/webp/gallery/1.webp';
})
}
And an amazing idea is using canvas.
function canUseWebP() {
var elem = document.createElement('canvas'); if (!!(elem.getContext && elem.getContext('2d'))) {
// was able or not to get WebP representation
return elem.toDataURL('image/webp').indexOf('data:image/webp') == 0;
} // very old browser like IE 8, canvas not supported
return false;
}
If you try webp in CSS, you need to use a high-level class.
.no-webp .elementWithBackgroundImage {
background-image: url("image.jpg");
}.webp .elementWithBackgroundImage{
background-image: url("image.webp");
}