Native lazy loading has arrived!

By Andy Potts

Lazy loading improves performance by loading resources, like images, when they’re required by the user. For example, when someone lands on your page it’ll load any images as they come into the viewport, rather than loading all of them when the page initially loads. This is beneficial because users won’t always see the images at the bottom of the page, so why make our users download all of those unnecessary -̶m̶e̶m̶e̶s̶- images?

Previously, if we wanted to implement lazy loading we would have had to import a library or write some Javascript to check the position of elements relative to the user's viewport and lazy load resources when necessary. Sounds like a bit of work, doesn’t it?

Native lazy loading is Google’s new built-in solution to this, meaning no additional Javascript needs to be written to include lazy loading (and hugely improve the performance of your website). Native lazy loading can be implemented as simply as adding the loading attribute to images or iFrames.

Sounds good, right? But is it actually worth implementing?

I decided to play around with implementing native lazy loading on one of our internal products at the BBC, a site that has ~3,000 active users per day. One of the most common actions on the site involves running a query which renders a list of up to 100 images — which I thought seemed like the ideal place to experiment with native lazy loading.

So, was it worth it? Yes! Adding the loading attribute to the images decreased the load time on a fast network connection by ~50% — it went from ~1 second to < 0.5 seconds, as well as saving up to 40 requests to the server 🎊. All of those performance enhancements just from adding one attribute to a bunch of images!

Worked example

So we’ve seen what it can do, let’s have a look at how it works. I’ll walk through how we might implement native lazy loading for images.

It’s really easy — attaching the loading attribute, with the value of “lazy” will tell the browser to lazy load the image. Specifying the height and width will prevent any janky page layout changes as the images load.

<img src="/images/example.png" loading="lazy" width="400" height="400" />
A simple native lazy loading codepen demo (take a look at the network inspector in Chrome 76 as you scroll down the pen).