Very much improved Image loading for Micro.blog
A few weeks ago I built a little hack for image loading on Micro.blog. Instead of serving a single fixed-size image, it provided multiple image sizes to allow browsers to decide which version to load based on screen size, pixel density, and, if supported, even network conditions. The problem was, that image loading somehow always felt a bit janky.
Inspecting the page didn’t reveal anything obvious, so I asked ChatGPT for help. The real issue turned out to be caching, or rather, the lack of it. Because I had encoded the target URL with urlquery
, the image paths varied slightly and the browser never reused them from cache. While we were at it, I also got a few suggestions for further improvements. I dropped the 1200px variant since my content column is never wider than 640px, reworked the hook so image URLs are now consistent, and added a few extras like cleaner srcset
/sizes
and LCP prioritization for the first image.
The pages now feel noticeably smoother, images appear instantly, and they still only use as much bandwidth as needed. Sometimes it really pays off to take a closer look at your own site and sweat the details. Here is the updated render-image.html
.
{{ $dest := .Destination | safeURL }}
{{ $alt := .Text | default "" }}
{{ $abs := cond (hasPrefix $dest "http") $dest ($dest | absURL) }}
{{ $isMB := or (hasPrefix $abs "https://micro.blog/photos/") (hasPrefix $abs "http://micro.blog/photos/") }}
{{ $src300 := "" }}
{{ $src600 := "" }}
{{ $src900 := "" }}
{{ if $isMB }}
{{ $src300 = (replaceRE `/photos/[^/]+/` "/photos/300x/" $abs) }}
{{ $src600 = (replaceRE `/photos/[^/]+/` "/photos/600x/" $abs) }}
{{ $src900 = (replaceRE `/photos/[^/]+/` "/photos/900x/" $abs) }}
{{ else }}
{{ $encoded := $abs | urlquery }}
{{ $src300 = printf "https://micro.blog/photos/300x/%s" $encoded }}
{{ $src600 = printf "https://micro.blog/photos/600x/%s" $encoded }}
{{ $src900 = printf "https://micro.blog/photos/900x/%s" $encoded }}
{{ end }}
{{ $isFirst := not (.Page.Scratch.Get "lcp_done") }}
{{ if $isFirst }}{{ .Page.Scratch.Set "lcp_done" true }}{{ end }}
<img {{ if $isFirst }}loading="eager" fetchpriority="high"{{ else }}loading="eager" fetchpriority="auto"{{ end }}
decoding="async"
src="{{ $src600 }}"
srcset="{{ $src300 }} 300w, {{ $src600 }} 600w, {{ $src900 }} 900w"
sizes="(max-width: 480px) 100vw,
(max-width: 768px) 80vw,
640px"
alt="{{ $alt }}">