Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preload responsive images in a <picture> tag

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?

like image 487
Jack Avatar asked Nov 15 '25 05:11

Jack


1 Answers

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

like image 141
ausi Avatar answered Nov 17 '25 22:11

ausi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!