// Get all the images with class "lazy" var images = document.querySelectorAll("img.lazy"); // Check if the image is in the viewport function isImageInViewport(image) { var rect = image.getBoundingClientRect(); var html = document.documentElement; return ( rect.top >= 0 && rect.left >= 0 && rect.bottom <= (window.innerHeight || html.clientHeight) && rect.right <= (window.innerWidth || html.clientWidth) ); } // Load the image if it's in the viewport function loadImage(image) { var src = image.dataset.src; if (src) { image.src = src; image.classList.remove("lazy"); } } // Loop through the images and load them if needed function checkImages() { for (var i = 0; i < images.length; i++) { if (isImageInViewport(images[i])) { loadImage(images[i]); } } } // Run the check on page load and scroll events window.addEventListener("load", checkImages); window.addEventListener("scroll", checkImages);