Preventing Content Reflow From Lazy-Loaded Images

Share this:

You know the concept of lazy loading images. It prevents the browser from loading images until those images are in (or nearly in) the browser's viewport.

There are a plethora of JavaScript-based lazy loading solutions. GitHub has over 3,400 different lazy load repos, and those are just the ones with "lazy load" in a searchable string! Most of them rely on the same trick: Instead of putting an image's URL in the src attribute, you put it in data-src — which is the same pattern for responsive images:

JavaScript watches the user scroll down the page

When the use encounters an image, JavaScript moves the data-src value into src where it belongs

The browser requests the image and it loads into view

The result is the browser loading fewer images up front so that the page loads faster. Additionally, if the user never scrolls far enough to see an image, that image is never loaded. That equals faster page loads and less data the user needs to spend.

"This is amazing!" you may be thinking. And, you’re right... it is amazing!

That said, it does indeed introduce a noticeable problem: images not containing the src attribute (including when it’s empty or invalid) have no height. This means that they're not the right size in the page layout until they're lazy-loaded.

When a user scrolls and images are lazy-loaded, those img elements go from a height of 0 pixels to whatever they need to be. This causes reflow, where the content below or around the image gets pushed to make room for the freshly loaded image. Reflow is a problem because it's a user-blocking operation. It slows down the browser by forcing it to recalculate the layout of any elements that are affected by that image's shape. The CSS scroll-behavior property may help here at some point, but its support needs to improve before it’s a viable option.

Lazy loading doesn't guarantee that the image will fully load before it enters the viewport. The result is a perceived janky experience, even if it’s a big performance win.

There are other issues with lazy loading images that are worth mentioning but are outside the scope of this post. For example, if JavaScript fails to run at all, then no images will load on the page. That’s a common concern for any JavaScript-based solution but this article only concerned with solving the problems introduced by reflow.

If we could force pre-loaded images to maintain their normal width and height (i.e. their aspect ratio), we could prevent reflow problems while still lazy loading them. This is something I recently had to solve building a progressive web app at DockYard where I work.

Maintaining aspect ratio

There are many ways to go about the way we can maintain aspect ratios. Chris once rounded up an exhaustive list of options, but here’s what we’re looking at for image-specific options.

The image itself

The image src provides a natural aspect ratio. Even when an image is resized responsively, its natural dimensions still apply. Here's a pretty common bit of responsive image CSS:

img {
max-width: 100%;
height: auto;
}

That CSS is telling images not to exceed the width of the element that contains them, but to scale the height properly so that there's no "stretching" or "squishing" as the image is resized. Even if the image has inline height and width attributes, this CSS will keep them behaving nicely on small viewports.

However, that "natural aspect ratio" behavior breaks down if there's no src yet. Browsers don't care about data-src and don't do anything with it, so it’s not really a viable solution for lazy loading reflow; but it is important to help understand the "normal" way images are laid out once they've loaded.

A pseudo-element

Many developers — including myself — have been frustrated trying to use pseudo-elements (e.g. ::before and ::after) to add decorations to img elements. Browsers don't render an image’s pseudo-elements because img is a replaced element, meaning its layout is controlled by an external resource.

However, there is an exception to that rule: If an image’s src attribute is invalid, browsers will render its pseudo-elements. So, if we store the src for an image in data-src and the src is empty, then we can use a pseudo-element to set an aspect ratio:

That'll set a 16:9 aspect ratio on ::before for any element with a data-src attribute. As soon as the data-src becomes the src, the browser stops rendering ::before and the image's natural aspect ratio takes over.

There are a couple drawbacks to this solution, however. First, it relies on CSS and HTML working together. Your stylesheet needs to have a declaration for each image aspect ratio you need to support. It would be much better if the template could insert an image without needing CSS edits.

Second, it doesn't work in Safari 12 and below, or Edge, at the time of writing. That's a pretty big traffic swatch to send poor layouts. To be fair, maintaining the aspect ratio is a bit of a progressive enhancement — there's nothing "broken" about the final rendered page. Still, it’s much more ideal to solve the reflow problem and for images to render as expected.

Data URI (Base64) PNGs

Another way we attempted to preserve the aspect ratio was to inline data URI for the src. as PNG. Using png-pixel.com will help with the lift of all that base64-encoding with any dimensions and colors. This can go straight into the image's src attribute in the HTML:

And, yes, this approach also comes with some drawbacks. Although the browser support is much better, it's complicated to maintain. We need to generate a base64 string for each new image size, then make that object of strings available to whatever templating tool that’s being used. It's also not the most efficient way to represent this data.

I kept exploring and found a smaller way.

Combine SVG with base64

After exploring the inline PNG option, I wondered if SVG might be a smaller format for inline images and here's what I found: An SVG with a viewBox declaration is a placeholder image with an easily editable native aspect ratio.

First, I tried base64-encoding an SVG. Here's an example of what that looked like in my HTML:

On small, simple aspect ratios, this is roughly equivalent in size to the base64 PNGs. A 1:1 ratio would be 114 bytes with base64 PNG and 106 bytes with base64 SVG. A 2:3 ratio is 118 bytes with base64 PNG and 106 bytes with base64 SVG.

However, using base64 SVG for larger, more complex ratios stay small, which is a real winner in file size. A 16:9 ratio is 122 bytes in base64 PNG and 110 bytes in base64 SVG. A 923:742 ratio is 3,100 bytes in base64 PNG but only 114b in base64 SVG! (That's not a common aspect ratio, but I needed to test with custom dimensions with my client's use case.)

Here’s a table to see those comparisons more clearly:

Aspect Ratio

base64 PNG

base64 SVG

1:1

114 bytes

106 bytes

2:3

118 bytes

106 bytes

16:9

122 bytes

110 bytes

923:742

3,100 bytes

114 bytes

The differences are negligible with simple ratios, but you can see how extremely well SVG scales as ratios become complex.

We've got much better browser support now. This technique is supported by all the big players, including Chrome, Firefox, Safari, Opera, IE11, and Edge, but also has great support in mobile browsers, including Safari iOS, Chrome for Android, and Samsung for Android (from 4.4 up).

🏆 We have a winner!

Yes, we do, but stick with me as we improve this approach even more! I remembered Chris suggesting that we should not use base64 encoding with SVG inlined in CSS background-images and thought that advice might apply here, too.

This is just a tad smaller than base64 SVG. The 1:1 is 106 bytes in base64 and 92 bytes when URL-encoding. 16:9 outputs 110 bytes in base64 and 97 bytes when URL-encoded.

If you're interested in more data size by file and encoding format, this demo compares different byte sizes between all of these techniques.

However, the real benefits that make the URL-encoded SVG a clear winner are that its format is human-readable, easily template-able, and infinitely customizable!

You don't need to create a CSS block or generate a base64 string to get a perfect placeholder for images where the dimensions are unknown! For example, here's a little React component that uses this technique:

I'm happy to report that browser support hasn't changed with this improvement — we've still got the full support as base64 SVG!

Conclusion

We've explored several techniques to prevent content reflow by preserving the aspect ratio of a lazy-loaded image before the swap happens. The best technique I was able to find is inlined and optimized URL-encoded SVG with image dimensions defined in the viewBox attribute. That can be scripted with a function like this:

I’ve been using that SVG technique for a little while on my WordPress blog for GIFs: I use the generated JPEG thumbnail as a background image to the <img>, and place the GIF’s URL in a data-gif-url attribute. The src attribute with the data URI for the SVG is generated on the fly when I insert it in my blog posts (with a little custom Gutenberg block that reads the file’s attributes). Then I simply overlay a button that’s toggle the src and data-gif-url attributes and that’s it!

It makes it a lot easier than having to resize each GIF to a certain aspect ratio. (and yes, I know it’s bad to use GIFs instead of a video file… I’ll find a solution for that later)

…but why not just use inline height and width attributes? That is the most semantic solution, and is guaranteed to work. Even better, it lets you use a 1px transparent png data url as a placeholder until the image starts to load.

But why not just use inline height and width attributes? Those are guaranteed to work, can be set per image, are the most semantic, and let you use a 1px transparent png dataurl as a placeholder until the image starts loading.

Using src has another big caveat: You are removing progressive loading/displaying of images, which results into much later shown image. This even happens with non progressive images and the difference is pretty heavy. So don’t use this technique.

Picture source not accept src attribute and when I set inline svg as srcset, bowser get me this error: “Failed parsing ‘srcset’ attribute value since it has an unknown descriptor.” Any suggestion how to set srcset as a inline svg? Thanks

I solved the reflow problem using tiny, highly-compressed, thumbnail images (e.g. 40×30) with the same aspect ratio as the larger image (e.g. 800×600). Thumbnails can be inlined but services such as Cloudinary can generate them on the fly.

The full image is then positioned absolutely over the top when required. (The full image is then made into a standard block and the thumbnail is removed – but that was only to prevent some janky behaviour in Edge.)

It might be interesting to know that this technique doesn’t work if the image ratios are different between screen sizes (e.g. 1:1 on small screens, 2:1 on large screens). The browser will only look for the src tag to define the element size and optimized URLs-encoded images are not accepted by the srcset tag for responsive images.

I could be wrong but that’s what I found out with the few tests I did this afternoon. I’d love to see if anyone know work-arounds for this particular case.

Rectification: This technique won’t work with srcset attribute as written above. The problem comes from the spaces included in the Optimized URL-encoded that browsers use for to separate the image URL and the width descriptor. To fix this issue, you’ll have to write the following :

It seems Safari on iOS 12 won’t trigger an observer event (in the IntersectionObserver polyfill) when the SVG placeholder enters the viewport. I’m investigating a workaround, but for now that makes this not a production-ready technique.

👋

CSS-Tricks* is created, written by, and maintained by Chris Coyier and a team of swell people. It is built on WordPress and powered up by Jetpack. It is made possible through sponsorships from products and services we like.