Link Preload as Image

I’ve been playing with these fancy new view transitions and my experience thus far is that they work ok on localhost, but as soon as I push code to a preview branch on a remote server, the image loads between transitions are janky because of image loading.

Animated gif of icon loading slowly between transitions.

Granted, transitions are behind a flag so unexpected glitches are expected.

But transitioning images across views — especially from a small thumbnail on a list view to a full size image on a detail view — seems like such a common use case. I’m sure they’ll figure this out

Bramus pointed out I should try preloading the image on the detail page.

Duh, I should be doing that regardless of whether I’m trying to make view transitions work!

In fact, on a site like my icon gallery, the large image icon is literally the “raison d'être” of the page itself — that’s what you’re there, to see the big, beautiful icon! There’s no asset more crucial on that page than that one, I should be preloading it!

There’s a nice web.dev article on the subject, but I like to get varying perspectives and explanations when trying to understand something. So I searched to learn more. Of course Chris had already written on it and explains it in the way only he can. And, again unsurprisingly, Stefan had a helpful resource on preloading too.

In essence, you want to tell the browser that a certain image exists on the page and is super important before the prescanner discovers it.

I think of it kind of like when I tell my wife a story about our kids. I start with, "Ok, don't worry, everyone is fine, but...[story about some crazy thing the kids did].” A little heads up goes a long ways.

On my icon detail page, I have:

<img src="icon.png" srcset="icon@2x.png 2x">

So, to tell the browser it’s gonna need that image before it parses to that point in the HTML, I include this in the <head>:

<link rel="preload" as="image" href="icon.png" imagesrcset="icon@2x.png 2x" />

If you're not up to speed on this one — like I was — might be a good ‘un to familiarize yourself with now.

Update 2023-05-26

Mark pointed out that Wordpress is eschewing <link> preloads in favor of fetchpriority directly on the img.

Their rationale is interesting. I like <link> because in theory it’s the fastest way for the browser to find out about a critical resource. But:

While [that approach] in principle allows the browser to know about loading the image even earlier, in practice there isn’t a notable difference, especially when using the tag, as at that point the entire HTML will already be loaded.

Given my SSG setup, it’s easy enough for me to do the <link> approach, so I’m going to stick with that. But for a CMS that doesn’t necessarily know about all resources during the lifecycle of creating a document, I can see why they opt for sticking fetchpriority directly on the image.