Search code examples
htmlimagegoogle-chromepreload

Preloading <picture> element loads two images


I have a <picture> element with multiple sources for multiple device widths and trying to assemble a correct <link rel="preload"> element to preload a single image that fits the media query defined for the <picture>. For some reason, my code results in browser loading two images when looking at Chrome devtool's Network tab.

What am I misunderstanding here?

<link rel="preload" as="image" imagesrcset="/big.webp 885w, /mobile.webp 420w, /fallback.jpg 885w" imagesizes="(min-width: 421px) 885px, (max-width: 420px) 420px">

<picture>
    <source srcset="/big.webp" type="image/webp" media="(min-width: 421px)">
    <source srcset="/mobile.webp" type="image/webp" media="(max-width: 420px)">
    <img src="/fallback.jpg" fetchpriority="high" width="885" height="570" class="img-fluid" alt="example">
</picture>

The two images that are loaded are

/big.webp and /mobile.webp

<link rel="preload" as="image" imagesrcset="https://via.placeholder.com/1200x800 885w, https://via.placeholder.com/1200x800/ff0000 420w, https://via.placeholder.com/1200x800/00ff00 885w" imagesizes="(min-width: 421px) 885px, (max-width: 420px) 420px">

<picture>
  <source srcset="https://via.placeholder.com/1200x800" type="image/webp" media="(min-width: 421px)">
  <source srcset="https://via.placeholder.com/1200x800/ff0000" type="image/webp" media="(max-width: 420px)">
  <img src="https://via.placeholder.com/1200x800/00ff00" fetchpriority="high" width="885" height="570" class="img-fluid" alt="example">
</picture>


Solution

  • I was only able to find a partial solution by setting two separate <link rel="preload"> elements with respective media attributes like so:

    <link rel="preload" as="image" imagesrcset="/big.webp"
    imagesizes="885px" media="(min-width: 421px)">
    
    
    <link rel="preload" as="image" imagesrcset="mobile.webp"
    imagesizes="420px" media="(max-width: 420px)">
    

    This way, only one of these images gets downloaded. The only issue is with the fallback.jpg image since it has the same size rule as the big.webp therefore cannot be defined like the others above (both images with the same size would get downloaded). I have to settle for this solution for the time being, unless someone comes up with a way to include all three images in the preload.