AndrewLeonardi
AndrewLeonardi

Reputation: 3512

Serve images in next-gen formats: Fallback Image?

As Google suggests for page performance I am adding webp images to my project. However I am aware that Safari does not support this image type so I am attempting to add a fallback png image for Safari users.

I used the set up below. This works as a fall back but now Google is telling me I'm using the wrong image type again. Is this not the correct set up?

<div class="carousel-item" 
style="background-image: url('http://a.webpurr.com/l8r1.webp'), 
url('https://i.imgur.com/fVmGtb3.png')">
</div>

Upvotes: 3

Views: 2569

Answers (1)

GrahamTheDev
GrahamTheDev

Reputation: 24835

If you list multiple background image sources they are all downloaded if they are all supported, Page Speed Insights then detects these image downloads and penalises you for it.

Many people do this, they are trying to optimise file size and end up downloading 2 images for every image by mistake.

Open the network tab in developer tools and run the snippet below, you will see two image requests are made (in browsers that support both formats)

The best scenario is to use browser support sniffing and swap out the image src dynamically before the image loads (providing fallback for no JavaScript) which is both complex and messy to do right.

Another option is to change the carousel to not use background images but instead use the HTML5 <picture> element as this will always return the first option it supports and also works in older browsers that don't support it if you need backwards compatibility.

<picture>
  <source srcset="img/awesomeWebPImage.webp" type="image/webp">
  <source srcset="img/creakyOldJPEG.jpg" type="image/jpeg"> 
  <img src="img/creakyOldJPEG.jpg" alt="Alt Text!">
</picture>

.demo{
  max-width : 400px;
  height: 400px;
  background-image: url("http://a.webpurr.com/l8r1.webp"),  url("https://i.imgur.com/fVmGtb3.png")
}
<div class="demo"></div>

Upvotes: 8

Related Questions