Quickly enhance your website’s performance by implementing lazy loading for images with this custom JavaScript snippet.
JavaScript
// Lazy Loading Images with Custom JavaScript
document.addEventListener("DOMContentLoaded", function () {
var lazyImages = document.querySelectorAll("img.lazy");
lazyImages.forEach(function (lazyImage) {
if (lazyImage.getBoundingClientRect().top < window.innerHeight &&
lazyImage.getBoundingClientRect().bottom > 0) {
lazyImage.src = lazyImage.dataset.src;
lazyImage.classList.remove("lazy");
}
});
var lazyLoadHandler = function () {
lazyImages.forEach(function (lazyImage) {
if (lazyImage.getBoundingClientRect().top < window.innerHeight &&
lazyImage.getBoundingClientRect().bottom > 0) {
lazyImage.src = lazyImage.dataset.src;
lazyImage.classList.remove("lazy");
}
});
};
window.addEventListener("scroll", lazyLoadHandler);
window.addEventListener("resize", lazyLoadHandler);
});
Usage
To use this code, follow these steps:
- Add the
lazy
class to the<img>
elements you want to lazy load. - Set the
data-src
attribute to the actual image source (src
). - Include the above JavaScript snippet on your page.
HTML
<img src="placeholder.gif" class="lazy" data-src="full-size.jpg" width="500" height="500">
FAQs
How does lazy loading improve website performance?
Lazy loading delays the loading of non-essential resources, like images, until they are about to be viewed. This reduces initial page load times, leading to a faster user experience.