How to do lazy loading in javascript

Learn how to do lazy loading in javascript to fetch any type of content.

Let us learn this buy building a lazy image loading feature.

What is lazy image loading?

Many websites like Facebook, Linkedin, Pinterest or ecommerce sites like Flipkart, Amazon have lots of image, They do no load all image at once on page load.

Instead what they do is load images as we scroll down or the image is in the viewport of the screen.

To achieve this functionality we will need to do three things.

1. We will store the image source in a custom HTML attribute so that we can use it to load the image.

<img data-src="https://cdn.pixabay.com/photo/2018/09/16/15/31/boy-3681679_1280.jpg" />

and may be use a class to access all the images at once.

<img class="lazy-image" data-src="https://cdn.pixabay.com/photo/2018/09/16/15/31/boy-3681679_1280.jpg" />

2. Check if the image is in the view port or visible in the screen. To do this we will calculate the difference between the image and the screen with a buffer.

We are using buffer so that image could be loaded even if it is half visible only.

//Buffer
let inAdvance = 100;

//This will check if the image is inside the viewport or not.
if(image.offsetTop < window.innerHeight + window.pageYOffset + inAdvance)

3. Now we have to create a function which will be doing the lazy loading and call this when window is scrolled or resized.

//Prefetch all the images
//Repeating this inside function will hamper the performance
let lazyImages = [...document.querySelectorAll('.lazy-image')];

//Buffer
let inAdvance = 50;
 
const lazyLoad = () => {
    //Iterate all the images and check
    lazyImages.forEach(image => {
        if (image.offsetTop < window.innerHeight + window.pageYOffset + inAdvance) { 
             //if image is in viewport set the src from custom attribute 
             //dataset is used to get the custom attribute
             image.src = image.dataset.src; 

             //if the image is loaded then add class to it 
             image.onload = () => image.classList.add('loaded')
        }
    });
};

//Call the function to load the first image 
lazyLoad();

//lazy load the function when window is scrolled
window.addEventListener('scroll', throttle(lazyLoad, 700));

//lazy load the function when window is resized
window.addEventListener('resize', throttle(lazyLoad, 700));

We are using throttle to limit the number of time a function can be called. It will be called again after the specified time only.

Here is the example of lazy image loading in javascript.