Lazy Load Images with LazySizes
March 23, 2021 • 2 min read
A quick introduction to a library that has better browser support than the loading="lazy" attribute.
THE PROBLEM
The images on our website load all at the same time, including the ones that are not in view, blocking other assets to be downloaded.
This makes our website take longer to load, and has a bad effect on our UX.
A SOLUTION
We are going to use a nice little package called LazySizes to make images load only when they are scrolled into view.
To do that we only need to:
- Replace the
srcattribute on images with adata-srcattribute, so the browser doesn’t download them automatically. Also, this allows LazySizes to take the image source in order to request it when scrolled into view. - Add a class of
lazyloadto the image, so LazySizes knows it has to act on that element.
Here’s a quick demo, scroll to make images appear. You can check the network tab on the browser’s DevTools and you’ll see image requests being done as you scroll!