Why should you load your images in a lazy way?
Among other reasons:
- Increase page speed
- Better page rank
- More visitors
- Reduce bounce rate
- Increase pages / session rate
- Improve user experience
- Reduce infrastructure costs
In a nutshell
This is the process:
- Modify all your tags by changing src by data-src or something else
- Add a specific class to every image we want to load lazily.
- Add a listener to know when the image is being displayed
- Once the image is displayed, the listener will call our code to modify our image tag
- The code will get the url from data-src and will update the src property.
- The image will be loaded by the browser
- Call the listener after the page loads
Straight to the point
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”
Include the script via CDN in your head tag of your page
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:
const observer = lozad(); observer.observe();
The last step is to modify all your images you want to load lazily.
<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.