Using WebP Images with Fallback

File sizes for WebP images are typically smaller than their JPEG and PNG counterparts. If your application involves showing a lot of images then probably it makes sense to add WebP support.

Considering the WebP format is created by Google, and Google’s Chrome browser has about a 60-65% market share, a lot of your users can be benefited if your application starts serving WebP images.

Detecting WebP Support with <picture> Tag

There are ways to detect WebP images using Javascript and server-side techniques (htaccess for example), but the most robust solution is to use <picture> tag for your images in the webpage. The <picture> tag has been created for these special cases, so it is best to use this to provide the best browser support.

See also  How to Justify Text using text-align & text-justify CSS Properties

The type tag attribute in a <source> tag specifies a file type for the source image.

<picture>
    <source srcset="https://usefulangle.com/image.webp" type="image/webp">
    <source srcset="https://usefulangle.com/post/114/image.jpg" type="image/jpeg">
    <img src="https://usefulangle.com/post/114/image.jpg">
</picture>

In the above markup :

  • Browsers supporting WebP (Chrome, Edge, Firefox, Safari, Opera) will display “https://usefulangle.com/image.webp” <source> element
  • Older versions of browsers not supporting WebP will fallback to “https://usefulangle.com/post/114/image.jpg” <source> element
  • Browsers not supporting the <picture> tag (Internet Explorer) will fallback to the <img> tag
See also  WordPress disable srcset responsive images

WebP Browser Support

As of June 23, 2020, all major browsers — Chrome, Edge, Firefox & Safari (14+) — support the WebP format.

Useful Resources

Leave a Reply

Your email address will not be published. Required fields are marked *