Loading an image without causing a layout shift
December 21, 2022
WARNING: This post is over a year old. Some of the information this contains may be outdated.
Loading an image without causing a layout shift, correctly maintaining the aspect ratio, and not degrading initial page load performance due to image size/weight was difficult to implement with support across all major browsers. This led to developers either ignoring the issues, or the frameworks writing component abstractions that produced code like:
<span> <-- needed to maintain aspect ratio
<span> <-- needed to maintain aspect ratio, CSS padding hacks
<img src="" style="" /> <-- inline styles to prevent layout shift
<noscript>...</noscript> <-- JS needed for IntersectionObserver
</span>
</span>
It’s a different story in 2022. There’s cross-browser support for: aspect-ratio
, width/height attributes to prevent layout shift, native image lazy-loading, and pure CSS/SVG-based blur-up image placeholders. The above code can drop the wrapping elements and work without runtime JavaScript needed.
<img
alt="A kitten"
decoding="async"
height="200"
loading="lazy"
src="https://placekitten.com/200/200"
style="aspect-ratio: auto 1 / 1"
width="200"
/>
Comments are not enabled for this post.