I'm working to optimise Largest Contentful Paint (LCP), but am having trouble preloading the correct amount of LCP candidate images based on device size.
The problem:
The desired solution:
My first thought was the obvious one, use the link
els' media
attribute to decide what to load; however, all resources are downloaded anyway (refs 1, 2).
I'm not a fan of my current best 'solution' for this: using link
's imagesrcset
+ imagesizes
attributes to load the first image regardless, and the latter images as 1px by 1px on small devices.
E.G.
<link
rel="preload"
as="image"
href="image1"
imagesrcset="image1-small 100w 200h,image1-large 200w 400h"
imagesizes="(max-width: 40em) 100vw, 400px"
>
<link
rel="preload"
as="image"
href="image2"
imagesrcset="image2-tiny 1w 1h, image2-small 100w 200h, image2-large 200w 400h"
imagesizes="(max-width: 40em) 1px, 400px"
>
Clearly very hacky. Is there a 'correct' way of doing this? Am I missing something?
So it transpires using the media
attribute for link
el's of the type="image"
does work.
Lesson learned to always test what I read :)
Therefore the following works to solve the issue at hand:
<link
rel="preload"
as="image"
href="image1"
imagesrcset="image1-small 100w 200h, image1-large 200w 400h"
imagesizes="(max-width: 40em) 100vw, 400px"
>
<link
rel="preload"
as="image"
href="image2"
imagesrcset="image2-small 100w 200h, image2-large 200w 400h"
imagesizes="400px"
media="(min-width: 40em)"
>