Frontend Performance: Using WebP in React
Images usually make up for the better part of the bytes on a website, so it is one of the most important things to evaluate when you optimize your website for frontend performance. Less bytes to download for the user equals better pagespeed index, better conversion rate and in general better user experience. It is also an important factor in ecommerce seo.
The most well known tricks to server fewer bytes to download are:
- Optimize the quality of the images
- Use JPG where possible
- Use srcset to serve different sized images for the different devices
Today tough, there is another way to reduce the size of the images, the relatively new image format webp. It supports both lossless and lossy and can be used both for images with and without transparency.
WebP size benefits
According to Google’s own studies, using webp will save an average of 30% of the an png image size, compared to what normally is served on the web. For jpg the savings are also so good that you should favor webp over jpg. Despite being smaller in size, it is able to retain the image quality so that you get the best of both worlds: smaller image and good quality.
This is something that we all get get onboard with!
Use Webp in React
The browser support for WebP is not 100% yet, at time of writing this blog post it is at 80%. Not too shabby, but we still need to provide a decent fallback for browsers that don’t support it yet.
The easiest way to do this is to utilize the HTML picture element, and provide two different sources, one with webp and one with the fallback. Like so:
<source srcSet=”img.webp” type="image/webp" />
<source srcSet=”img.jpg” type="image/jpeg" />
<img src=”img.jpg” alt="Alt text" />
Our friends at Snowball created a nice pen on Codepen for us, demonstrating how this plays out in React. The source that the browser decides to load is displayed beneath the image.
Here’s is how it looks in the latest Safari.
And here’s is how it looks in Chrome
Great! The browser to determines which image to use, and Chrome is wise enough to choose webp. Safari has no support for WebP yet, so their users are getting the fallback jpg version instead.
Use WebP. It is as simple as that. Make sure you are using a media service that provides this for you. If you are using Crystallize already, you already have this. We are generating both WebP and original file format for every image you upload, ready distributed on a CDN. Enjoy!