Type to search. Arrow keys to move, Enter to open, Esc to close.

All research
Web publishingState as of: 2026-10

Build-time image optimization

Which image optimizations a static site build can apply to every image without editing templates, and the traps found on the way.

Research question: Which image optimizations can the build apply without editing templates by hand, and what has to be watched?

Project requirement

Image-heavy small static sites loaded slowly and shifted their layout on mobile. Templates should not need manual attributes on every image.

Method and validation

  • Post-processing of the rendered HTML: every img tag gets attributes based on the real file.
  • width and height from the actual image size, unless the tag already has them.
  • Images in the header and the first image in main get fetchpriority="high"; the other images below the navigation get loading="lazy".
  • Smaller WebP variants (480, 800 and 1200 px, only below the source width, quality 82) with srcset and sizes, but only for CSS classes whose width the CSS fixes.
  • Variants are cached by content hash, so a rebuild does not encode them again; a separate script converts source images to WebP with EXIF rotation and a size limit.
  • pytest for the image attributes, and the sample sites checked in a browser.

Findings

  • width and height reserve the space (lower CLS); with width: auto and height: auto in the CSS they only set the aspect ratio.
  • srcset is only safe for images with a fixed CSS width: with width: auto the browser takes the sizes value as the natural width and the image shrinks.
  • The main image must never be lazy; the build decides it from the header and the first image in main.
  • Converting every image would also have turned the shared favicon into WebP and broken per-site overrides, so the shared favicon is WebP from the start.
  • Without the image cache every build would encode the variants again.

Decision

The build adds size, priority and lazy loading to every image automatically, and srcset only for the listed fixed-width classes. Converting source images is a separate, manual step.

Limits and open questions

  • HTML processing uses regular expressions; that is enough for the generator's own templates, not for foreign HTML.
  • No AVIF variants; WebP works in every modern browser.
  • No real-user Core Web Vitals data (low traffic); Lighthouse lab data is the reference.

Sources