Use lazysizes to lazy-load images
Lazy-loading is the strategy of loading resources as they are needed, rather than in advance. This approach frees up resources during the initial page load and avoids loading assets that are never used.
Images that are offscreen during the initial pageload are ideal candidates for this technique. Best of all, lazysizes makes this a very simple strategy to implement.
What is lazysizes? #
lazysizes is the most popular library for lazy-loading images. It is a script that intelligently loads images as the user moves through the page and prioritizes images that the user will encounter soon.
Add lazysizes #
It is simple to add lazysizes:
- Add the lazysizes script to your pages.
- Choose the images you want to lazy-load.
- Update the
<img>
and/or<picture>
tags for those images.
Add the lazysizes script #
Add the lazysizes script to your pages:
<script src="lazysizes.min.js" async></script>
Update <img>
and/or <picture>
tags #
<img>
tag instructions
Before:
<img src="flower.jpg" alt="">
After:
<img data-src="flower.jpg" class="lazyload" alt="">
When you update the <img>
tag you make two changes:
- Add the
lazyload
class: This indicates to lazysizes that the image should be lazy-loaded. - Change the
src
attribute todata-src
: When it is time to load the image, the lazysizes code sets the imagesrc
attribute using the value from thedata-src
attribute.
<picture>
tag instructions
Before:
<picture>
<source type="image/webp" srcset="flower.webp">
<source type="image/jpeg" srcset="flower.jpg">
<img src="flower.jpg" alt="">
</picture>
After:
<picture>
<source type="image/webp" data-srcset="flower.webp">
<source type="image/jpeg" data-srcset="flower.jpg">
<img data-src="flower.jpg" class="lazyload" alt="">
</picture>
When you update the <picture>
tag you make two changes:
- Add the
lazyload
class to the<img>
tag. - Change the
<source>
tagsrcset
attribute todata-srcset
.
Verify #
Open DevTools and scroll down the page to see these changes in action. As you scroll, you should see new network requests occur and <img>
tag classes change from lazyload
to lazyloaded
.
Additionally, you can use Lighthouse to verify that you haven't forgotten to lazy-load any offscreen images. Run the Lighthouse Performance Audit (Lighthouse > Options > Performance) and look for the results of the Defer offscreen images audit.