2

I need to preload responsive images that are set in a <picture> tag:

<picture>
<source sizes="(max-width: 320px) 320px, (max-width: 480px) 480px, (max-width: 768px) 768px, (max-width: 1024px) 1024px, (max-width: 1200px) 1200px, 1500px" srcset="home-image1-bis2-1200x640.webp 1200w, home-image1-bis2-1024x546.webp 1024w, home-image1-bis2-768x410.webp 768w, home-image1-bis2-480x256.webp 480w, home-image1-bis2-320x171.webp 320w, home-image1-bis2.webp 1500w" type="image/webp">
</picture>

I've found this link: https://web.dev/preload-responsive-images/ and I tried to apply it like this:

<link rel="preload" href=home-image1-bis2-320x171.webp" as="image" type="image/webp" media="(max-width: 320px)">
<link rel="preload" href="home-image1-bis2-480x256.webp" as="image" type="image/webp" media="(min-width: 320.1px) and (max-width: 480px)">
<link rel="preload" href="home-image1-bis2-768x410.webp" as="image" type="image/webp" media="(min-width: 480.1px) and (max-width: 768px)">
<link rel="preload" href="home-image1-bis2-1024x546.webp" as="image" type="image/webp" media="(min-width: 768.1px) and (max-width: 1024px)">
<link rel="preload" href="home-image1-bis2-1024x546.webp" as="image" type="image/webp" media="(min-width: 1024.1px) and (max-width: 1200px)"><link rel="preload" href="home-image1-bis2.webp" as="image" type="image/webp" media="(min-width: 1200.1px)">

It doesn't seem to be working, also the console now logs this notice:

The resource home-image1-bis2-480x256.webp was preloaded using link preload but not used within a few seconds from the window's load event. Please make sure it has an appropriate as value and it is preloaded intentionally.

And this has no impact on the LCP of the lighthouse score.
How do I load the images properly?

Kimmax
  • 1,658
  • 21
  • 34
Jack
  • 21
  • 4

1 Answers1

2

You can use the imagesrcset and imagesizes attributes for this use case:

<link 
    rel="preload"
    as="image"
    type="image/webp"
    imagesrcset="home-image1-bis2-1200x640.webp 1200w, home-image1-bis2-1024x546.webp 1024w, home-image1-bis2-768x410.webp 768w, home-image1-bis2-480x256.webp 480w, home-image1-bis2-320x171.webp 320w, home-image1-bis2.webp 1500w"
    imagesizes="(max-width: 320px) 320px, (max-width: 480px) 480px, (max-width: 768px) 768px, (max-width: 1024px) 1024px, (max-width: 1200px) 1200px, 1500px"
>

See https://html.spec.whatwg.org/multipage/semantics.html#attr-link-imagesrcset
and https://html.spec.whatwg.org/multipage/semantics.html#attr-link-imagesizes

ausi
  • 7,253
  • 2
  • 31
  • 48
  • 1
    These are currently not supported in Safari: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link#browser_compatibility – Cykelero Feb 10 '22 at 17:12