Intersection Observer for image rendering on webpage

The Intersection Observer API observes changes in the intersection of a target element with document’s viewport.

I will show how to implement Intersection Observer API for image rendering. Using this API, only images present in the viewport will be loaded. This will reduce requests for fetching images on page load thus improving page performance significantly.

HTML Code overview –

Step 1: First of all create multiple image tags.
Step 2: Assign data-src to each image tag(src should be empty).

JAVASCRIPT code overview-

Step 1: Create new IntersectionObserver

const io = new IntersectionObserver(function (image_tags) {
});

Step 2: Start observing each image with data-src attribute

document.querySelectorAll('img[data-src]').forEach(function(image_tag) {
    io.observe(image_tag);
});

Step 3: Check image position with respect to viewport

// Element enters the viewport
if(image_tags[0].intersectionRatio !== 0) {
    set_image_src(image_tags[0].target);
    // Element leaves the viewport
} else {
    console.log("invisible");
}

Step 4: Assign src to image in viewport

function set_image_src(image_tag){
    image_tag.src = image_tag.dataset.src;
};

Find demo and code on github.

Leave a Reply

Your email address will not be published. Required fields are marked *