menu
Arm holding phone

The "New" Way To Solve Image Jank

Have you ever been reading an article on a site and just as you start reading, the line you are on jumps down the page? Then it jumps again?! Your pulse skyrockets and you think:

Holy crap, I didn’t want to read this article THAT much anyway, screw this!

And then you leave, likely never to return.

It’s a shame. The article could have been amazing, but all this chaos didn’t give a chance to read it.

25 years ago this wasn’t a problem. It’s 2020, what the hell happened?

The Problem

For today’s multi-device world, developers have to make sure images look great on a wide variety of screen sizes using Responsive Design. To accomplish this, a css rule is often used.

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

With this, it didn’t matter what width/height you had on your image. It was ignored and your css rule would override it. Naturally over the last 10 years, people started omitting height and width attributes.

Responsive images have a dirty little secret, they cause JANK.

Since the browser has no idea how big an image is until it starts downloading it, it can’t reserve any space in the layout as it tries to render the page. This causes the layout to jump when it finally knows the image size.

The Solution

At the end of 2019, Chrome and Firefox released a patch that uses the old width and height attributes to help with this problem. They use them to calculate a ratio and reserve the space in the layout just like the good ol’ days! Note: Safari’s patch is coming soon (v13.2)

<img src='ponypower.jpg' width="250" height="100" alt="My Little Pony With Cape"/>

Example Time

Left (old way with jank), Right (new way, no jank)

What About SrcSet?

Yes, you can even use this on images with a srcset. Keep in mind, it likely won’t work (yet) for sets where the image ratio changes. For example if you had a square image for mobile and a rectangular image for desktop.

Web Vitals: Cumulative Layout Shift (CLS)

Using this technique you can drastically improve your CLS score in web vitals! CLS is the measure of jank over the lifetime of a pageview, so the more jank you can prevent the better your score.

The Google Webmaster Blog has already mentioned Web Vitals will be used in search engine rankings next year so it’s a great idea to jump on this now.

Conclusion

Well just like fashion, what’s old is new. I’m surprised it took over 10 years for someone to step up and fix this problem. I’d like to give a shout out to Jen Simmons and her amazing work in Mozilla for pushing this forward.