WebP images are Google's alternative to PNG, jpeg, and jpg; providing smaller sized images - typically resulting in a 25% - 50% reduction in filesize. This significantly decreases page sizes and improves your website performance.
YouTube found that switching to WebP thumbnails resulted in 10% faster page loads.
Facebook experienced a 25-35% filesize savings for JPEGs and an 80% filesize savings for PNGs when they switched to using WebP.
๐กsource(web.dev)
Why should you care?
Firstly, if you're serving your images in the tiniest jpg file possible but still get warnings such as serve images in next-gen formats, it means there is more than could be done with optimizing the images on your website which directly impacts the performance.
๐ก WebP and AVIF are the recommended alternate image formats but we will be talking about WebP in this article
How do you use WebP in your projects?
Convert Images to WebP
You can do this using the cwebp command-line tool or the Imagemin WebP plugin (npm package).
If you are on MacOS, you can install cwebp with Homebrew:
brew install webp
On other OS such as Windows, you would need to download the libwebp package from their documentation
I downloaded the libwebp-1.4.0-windows-x64.zip. Also, remember to add it to your C:path
Convert the files
You can convert a single file, using cwebp's default compression settings:
cwebp images/flower.jpg -o images/flower.webp
or you can convert a single file, using a quality level of 80
:
cwebp -q 80 images/flower.jpg -o images/flower.webp
or you can convert all files in a directory:
for file in images/*; do cwebp "$file" -o "${file%.*}.webp"; done
Also, recall that you can install the imagemin library and use it.
Using WebP Images in your project
In order to understand the format of serving WebP pages in your projects, we need to examine its browser compatibility
As we can see, webP is supported by almost every major browser (except of course Internet Explorer). In addition, there are older versions that may not directly support WebP.
Therefore, instead of outrightly using our webP images in <img/>
tag, we take advantage of HTML <picture/>
to define multiple image src such that if a browser does not support webP file format, there is a fallback.
import FlowerWebp from 'images/flower.webp'
import FlowerJpg from 'images/flower.jpg'
<picture>
<source srcSet={FlowerWebp} type='image/webp' />
<img src={FlowerJpg} alt='Close-up of a vibrant red rose with dewdrops on its petals' />
</picture>
Next steps.
Measure that your images are now optimized by ~50% by using WebP. Run the Performance Audit (Lighthouse > Options > Performance) again. Lighthouse will list any images that are not being served in WebP.
Happy coding!