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:
- on small screens, a single image shows in a carousel
- on larger screens, up to four images can show
- I don't have control of the size of said images, meaning any can be a LCP candidate
- loading all four images on small devices is a no go: a waste of bandwidth and a performance hit
The desired solution:
- preload only one image on small screens
- preload all four images on large devices
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?