Use lazysizes to lazyload 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. lazysizes is a good choice because it uses the highly performant Intersection Observer API (where available) to detect the visibility of page elements. This makes it more performant than older solutions that use approaches like event handlers.
It is simple to add lazysizes:
- Add the lazysizes script to your pages.
- Choose the images you want to lazy-load.
- Update image tags for those images.
Add the lazysizes script
Add the lazysizes script to your pages:
<script src="lazysizes.min.js" async></script>
Update image tags
When you update the image tags you make two changes:
- Add the
lazyloadclass: This indicates to lazysizes that the image should be lazy loaded.
- Change the
data-src: When it is time to load the image, the lazysizes code sets the image
srcattribute using the value from the
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
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.
See it in action
Learn more and put this guide into action: