Simplest Way to Add Lazy Loading for Images
It’s never too early to start optimizing your site’s load times. Users have no patience. They give up if the site hasn’t loaded in a few seconds. There are many optimization techniques to incorporate — I recommend starting with using the built-in img
attributes. We’re going to introduce the loading attribute that enables lazy loading.
Default browser behavior
By default, browsers will load all the content , such as text, images, video, etc., on the page. The page would load quickly if it had mostly text, but when there are many images, the load time will be much longer. Imagine you’re shopping for a shirt and it takes half a minute for all 100 shirt images to load. Wouldn’t it be better if the browser loaded the visible items first and as you scrolled it loaded the next batch? That is lazy loading.
Built-in lazy loading feature
Lazy loading images will load only the images that are required, i.e. are in the viewport. There is now a built-in feature for img
to support lazy loading! This wasn’t always the case and libraries were created to make this possible.
At this point we’ve been displaying img
with a src
attribute.
<img src="<PATH_TO_IMG>" />
We’re going to use the loading attribute that tells the browser when to load the image. There are two values for the attribute:
- Eager: This is the default value. When no loading attribute is set, this is how the image is loaded. The image is loaded right away even if it’s not in viewport yet.
- Lazy: The browser determines if the image is close enough to the viewport and then loads the image when it is
<img src="<PATH TO IMG>" loading="lazy" />
It’s that easy!
Browser support for lazy loading
At the time of this writing in 2022, loading doesn’t have full browser support yet. There is full support on Chrome and partial support on Safari and Firefox. When you use it, be sure to check the browser support to see if you need a fallback solution.
Also keep in mind is that each browser has its own approach to the lazy loading of images. The behavior may vary slightly among the browsers.
Try lazy loading with different image sizes and test across a few browsers and screen sizes. If you’d like more information on how to get started with testing check out this post on testing strategy.
Using lazy loading for image is one of the quickest win. It’ll help a lot with performance as you start to look into additional optimizations, such as:
- Use image content delivery networks (CDN)
- Shrink images and use srcset with them
- Split code in multiple bundles
You won’t need to optimize everything at once. I recommend start off with using loading attribute for img
because there’s no setup and you’ll see immediate improvements.