OMONP#2: Image Lazy Loading With LazySizes
A quick introduction to a library that has better browser support than the loading=”lazy” attribute.
Welcome to issue #1 One Minute, One NPM Package, where you discover cool NPM packages and how to use them in one minute.
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.
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 a
data-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!