Posted on Aug 12, 2020
Among other reasons:
This is the process:
I will use a third-party library called lozad. It’s pretty small and it loads super fast so it won’t have a big impact in your page loading.
From Lozad docs:
"Highly performant, light and configurable lazy loader in pure JS with no dependencies for images, iframes and more, using IntersectionObserver API"
Unfortunately, you cannot use async property here since the script must be loaded before the page loads.
Add this code in your page
Of course you can move this code to a different script file (let say common.js) instead of your page. You only have to make sure that your file common.js is downloaded and ready to use before lozad call:
The last step is to modify all your images you want to load lazily.
const observer = lozad(); observer.observe();
<img src="image.jpg" class="yourClass" alt="your image description" />
<img data-src="image.jpg" class="lozad yourClass" alt="your image description" />
You can see more options here https://apoorv.pro/lozad.js/
It’s important you add alt="your image description" because that text will be displayed while the image is loading. This will give a better user experience to your visitors.