Lazy load offscreen images with lazysizes
Lazy loading is the approach of waiting to load resources until they are needed, rather than loading them in advance. This can improve performance by reducing the amount of resources that need to be loaded and parsed on initial page load.
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.
Add the lazysizes script to the page #
- Click Remix to Edit to make the project editable.
lazysizes.min.js has already been downloaded and added to this Glitch. To include it in the page:
- Add the following
<script src="lazysizes.min.js" async></script>
<!-- Images End -->
lazysizes will intelligently load images as the user scrolls through the page and prioritize the images that the user is going to encounter soon.
Indicate the images to lazy load #
- Add the class
lazyloadto images that should be lazy loaded. In addition, change the
For example, the changes for
flower3.png would look like this:
<img src="images/flower3.png" alt="">
For this example, try lazy loading
See it in action #
That's it! To see these changes in action, follow these steps:
To preview the site, press View App. Then press Fullscreen .
Open the console and find the images that were just added. Their classes should change from
lazyloadedas you scroll down the page.
- Watch the network panel to see the image files load individually as you scroll down the page.
Verify using Lighthouse #
Lastly, it's a good idea to use Lighthouse to verify these changes. Lighthouse's "Defer offscreen images" performance audit will indicate if you've forgotten to add lazy loading to any offscreen images.
- To preview the site, press View App. Then press Fullscreen .
- Press `Control+Shift+J` (or `Command+Option+J` on Mac) to open DevTools.
- Click the Lighthouse tab.
- Make sure the Performance checkbox is selected in the Categories list.
- Click the Generate report button.
- Verify the Defer offscreen images audit was passed.
Success! You have used lazysizes to lazy load the images on your page.