Open leoj3n opened 4 months ago
Thanks for the detailed writeup! Definitely open for discussion.
However, notice this will only allow to preload one "type" of image.
The thing is preloading only shaves off milliseconds, but serving next-gen images is doing the heavy lifting and may save hundreds of kb of bandwidth. There's definitely much opportunity for optimisations though. Will circle back to this.
I was able to up my lighthouse from 89/94 to 99 thanks to preloading, but keep in mind this is for an image the incures the network request 304
dance.
Here is something that may be possible in the future as a browser feature but maybe someone has an idea how to do it now...
If not using the
picture
element, something like the following is possible to preloadsizes
andsrcset
ofimg
:For an image like that:
However, notice this will only allow to preload one "type" of image.
This actually works well if linking to an endpoint that uses headers to dynamically send back the supported "type" to the browser, and
304
when cache isno-change
. This caching strategy always incures a network request which is not necessarily ideal, but it is nice to be able to preload.For instance when using the Vercel image optimization endpoint by updating
srcset
to be like that:Supported
jpeg/avif/webp
image types will be served dynamically which avoids having to use thepicture
element to tell the browser about the various available "types".If you wanted to preload sources in the
picture
element, they say this is possible:https://web.dev/articles/preload-responsive-images#preload_and_picture
Which would be the preload directive for that:
But unfortunately this isn't really what we want, as this only accounts for one "type" at a time (
"image/jpeg"
in this case). If you wanted to preload for"image/avif"
and"image/webp"
as well I don't think it would be possible using this method. You wouldn't want to use this method when those other types are enabled as it would cause the jpeg to download in addition to the avif/webp, depending.I'm wondering if a custom endpoint and single
img
tag like when using Vercel would be a viable solution for when you want to preload. Otherwise I think you have to just restrict yourself to one format (jpeg
), and use the single<img />
tag.So for now you could easily have a
preload
option that, when enabled, ignores any provided "types" and injects<link as="image" rel="preload" ... />
intosvelte:head
. I think that's a reasonable compromise to be able to preload.As an alternative, you could provide guidance on how to set up an endpoint in SvelteKit that returns the correct image type for the requested image url via header analysis (
Accept: image/avif,image/webp,image/apng,image/svg+xml,...
). It would need to know how to304
if the browser has the image cached (If-Modified-Since
/Etag
).