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');
}
I read some reference
what reference, so we don't just double up on the information you've already researched – Ronnyronsard