Simple Lazy loading images using Javascript

In this article, we are going to lazy load images in a webpage using JavaScript. We will be making request to load images in a webpage only when the image is visible in current viewport.

Follow this video for complete guidance :

 

Lazy Load Image Function in JavaScript

function lazyload(){
  var lazyImage = document.getElementsByClassName('lazy');
  for(var i=0;i<lazyImage.length;i++){
    if(elementinViewport(lazyImage[i])){
      lazyImage[i].setAttribute('src',lazyImage[i].getAttribute('data-src'));
      lazyImage[i].classList.remove('lazy');
    }
  }
}

JavaScript Function to check if the element is in viewport or not

function elementinViewport(el){
  var rect = el.getBoundingClientRect();
  return (
    rect.top >= 0 &&
    rect.left >=0 &&
    rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
    rect.right <= (window.innerWidth || document.documentElement.clientWidth)
  );
}

Trigger the lazy load function on scroll event

window.onscroll = function(){
  lazyload();
}

 

Recommended For You

About the Author: Ritesh Ghimire

Ritesh is a Computer Engineer, Web Developer and an active cricket follower.