Fix “Serve images in modern formats” for CSS Background Images
Trying to improve your PageSpeed score but getting dinged because you are fail to “Serve images in modern formats” for your background image CSS?
Fix for Serve Images in Modern Formats
There is a relatively easy fix that you can put in place which will serve a webp image while also using a non-webp (png, jpg, gif) as a backup for any browser that does not support webp images.
If you do not have a webp version of the image you want to use – you can use a free online tool like Cloud Convert WEBP Converter to easily create a webp version from any png, jpg, or gif image. Once you have a webp version of the image you can then add it to your files (in this example the file name would be bg-image.webp (and the original is bg-image.jpg) and is located in a directory called assets/images/ and then reference it within your CSS like this:
section.bg-image {background-image:url('assets/images/bg-image.jpg');} /* Use WebP if supported */ @supports (background-image: url('assets/images/bg-image.webp')) { section.bg-image {background-image: url('assets/images/bg-image.webp');} }
That code then will load the supported image to the browser and Google will no longer give an error for “Serve images in modern formats” for that background image in your CSS.
Documentation:
https://developer.chrome.com/docs/lighthouse/performance/uses-webp-images
https://developer.mozilla.org/en-US/docs/Web/CSS/@supports#syntax