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"
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/lozad/dist/lozad.min.js"></script>
Unfortunately, you cannot use async property here since the script must be loaded before the page loads.
Add this code in your page
<script type="text/javascript">
// I assume you are using jQuery. Otherwise you can use the classic way
$(document).ready(() => {
// to load images in a lazy way
// lazy loads elements with default selector as '.lozad'
const observer = lozad();
observer.observe();
console.info('lozad observing...');
});
</script>
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.
Before:
<img src="image.jpg" class="yourClass" alt="your image description" />
After:
<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.