While developing Royal Ur (https://royal-ur.com) I remembered the Audit feature in the Chrome Dev Tools. I fixed a couple of things and then came across the following hint: "Serve images in next-gen formats".
I decided that it was time to properly learn about WebP, a file format developed by Google in 2010, which is now supported by Chrome/Chromium, Edge and Firefox. As I wanted to support all the browsers not supporting WebP, my first idea was to use the CSS @supports
feature. Turns out there unfortunately is no @supports(webp)
.
JavaScript feature detection was not an option either. I did not want to rely on JavaScript for this and JavaScript still blocks rendering in browsers.
After more searching I came across https://engineering.naukri.com/2015/11/optimizing-css-background-images-using-webp/. They suggest using a combination of @media
and @supports
to detect features that were added to browsers at the same time or after support for WebP was added. Their approach unfortunately has two drawbacks: a) Firefox does not get WebP but does support it b) Safari gets WebP but does not support it.
So with all this information and the great list of browser hacks at http://browserhacks.com/ I set out to write WebP detection in CSS. This is the result:
I hope this is useful for somebody. Let me know what you think!
Top comments (4)
Quick note to autoprefixer and/or styled-components users out there - there's a bug that will cause Firefox's query to break. In order to fix is, add a second pair of parentheses:
This does not work.
Testing against googles own example repo
googlechrome.github.io/samples/pic...
Successfully get webp url of via.placeholder.com/200x150.webp with
media="(min-width: 650px)"
replace with your query and it disappears
Super helpful.
Has anyone been able to create a selector for Safari@14, since that browser also has webp-support?