Smarter image loading for Micro.blog
I just updated my Micro.blog theme to deliver images in a more efficient and responsive way. This means faster page loads, lower data usage, and no more compromises on image quality.
The trick? A clever use of Hugo’s Markdown render hooks, which Micro.blog supports via its theme templates. Shoutout to this helpful thread on the Micro.blog Help Forum, which showed me how to combine srcset
, sizes
, and Hugo templating to give the browser more flexibility.
Instead of serving a single fixed-size image, I now provide multiple image sizes. This allows the browser to decide which version to load based on screen size, pixel density, and, if supported, even network conditions.
Here is how it works:
Create a file at layouts/_default/_markup/render-image.html
in your Micro.blog theme with the following code:
{{ $path := .Destination | urlquery }}
<img
loading="lazy"
decoding="async"
src="https://micro.blog/photos/600x/{{ $path }}"
srcset="
https://micro.blog/photos/300x/{{ $path }} 300w,
https://micro.blog/photos/600x/{{ $path }} 600w,
https://micro.blog/photos/900x/{{ $path }} 900w,
https://micro.blog/photos/1200x/{{ $path }} 1200w"
sizes="(max-width: 480px) 100vw,
(max-width: 768px) 80vw,
(max-width: 1024px) 60vw,
50vw"
alt="{{ .Text }}" />
What it does:
- Mobile devices get smaller images, desktops get higher-res ones
- High-density screens such as Retina can load sharper versions if needed
- Browsers may choose smaller images on slow connections or in data-saver mode
- Lazy loading loads images only when they scroll into view
Previously, I used a bunch of iOS Shortcuts and external tools to downscale images before uploading them, which worked, but was tedious. Now, that extra workflow is no longer necessary. I can upload the full image and let Hugo and the browser do the rest.
The caveat is that most of my older posts won’t benefit from this. To make them compatible, I would have to swap in the original high-resolution files and replace all HTML-based image embeds with Markdown. That is unlikely to happen, unless I’m really bored someday. Nevertheless, it’s a small change with a big impact going forward, and I love it.