I’ve been converting some images on a website I’m working on to webp to optimize page-load times and score higher on lighthouse and all of that.
I used fallbacks in my code such as below:
.flex {
display: flex;
justify-content: space-around;
background: #ddd;
padding: 5px 0;
}
<div class="flex">
<div>WEBP image:<br> <img src="https://www.gstatic.com/webp/gallery/1.sm.webp" style="height: 80px;" /></div>
<div>JPG image:<br> <img src="https://www.gstatic.com/webp/gallery/2.sm.jpg" style="height: 80px;" /> </div>
<div>Fallback image (JPG):<br> <img src="https://www.gstatic.com/webp/gallery/4.sm.jpg" style="height: 80px;" />
</div>
</div>
<div>
Test image:<br>
<picture>
<source srcset="https://www.gstatic.com/webp/gallery/1.sm.webp" type="image/webp">
<source srcset="https://www.gstatic.com/webp/gallery/2.sm.jpg" type="image/jpeg">
<img src="https://www.gstatic.com/webp/gallery/4.sm.jpg">
</picture>
</div>
I’m obviously testing on Chrome because I know Safari doesn’t support WEBP, but it seems my chrome is always falling back on the jpeg and png files. When I inspect, I see the WEBP is in the code, and I can click it and it opens from the server so it is there. But Chrome isn’t using it to render the page, it’s immediately falling back on legacy formats.
I’ve been pulling my hair trying to figure out why it’s not working–maybe I used the picture tag incorrectly, etc…–but no solution.
Finally, I linked Modernizer in my layout, and saw that it wasn’t inserting any webp class into the html element. So I added a short script below it to see what’s happening, as below:
<script> if (Modernizr.webp) { console.log('webp supported'); } else { console.log('webp not supported'); } </script>
And the console logged the else webp not supported
.
At this point, I’m lost. I’ve trying looking up online, and I see no mention of Chrome dropping WEBP support or anything. My only guess is that I’m omitting and obvious declaration or something.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
It seems I was just getting fooled by a bug (or maybe it’s intentionally that way) chrome inspect tool. Since my fallback was the exact same image as the webp, just in jpg format, when I inspected the element it always highlighted the jpg fallback and I assumed that was being rendered instead of webp. I replaced the fallbacks with the random jpgs @isherwood put in the edited code, and Chrome still highlights the jpg image as the source even though it’s displaying the webp image above it in the code. So webp is working, I was just fooled by a faulty Chrome inspection.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0