How to serve a .JPG for browser that not support .webp in a proper way?

L.885 picture L.885 · Dec 24, 2018 · Viewed 8.7k times · Source

I am planning to use WebP on my E-Commerce website.It can boost a performance a lot based on Lighthouse test. But the problem is. we still have user that use iOS which does't have support for WebP format. I need more information about the proper way to deliver the images also how to let user download the images in JPG.

On my server. I have both formats for fallback purpose.

Answer

Narendra picture Narendra · Dec 24, 2018

The easiest way to use picture element. The browser will consider each child element and choose the best match among them; if no matches are found, the URL of the element's src attribute is selected.

<picture>
    <source srcset="/media/examples/surfer-240-200.webp" type="image/webp">
    <img src="/media/examples/painted-hand-298-332.jpg" />
</picture>

EDIT: As per Jaromanda's suggestion, we should look for fallback in img tag itself as internet explorer doesn't support picture element.

 <img src="image.webp" onerror="this.onerror=null; this.src='image.png'">

if we want to make sure that browser only downloads one file: a WebP or a fallback image; not both. We can use data-in attributes and assign the appropriate source based one browser support but in that we need to check for os/browser upfront.

 <img data-jpg="image.jpg" data-webp="image.webp" id="myimg"> 

and in JS

let img = document.getElementById('myimg');
 if(supportedBrowser){
   img.src = img.getAttribute('data-webp');
 }else{
   img.src = img.getAttribute('data-jpg');
 }