Lazy loading identifies resources as non-blocking and loads them only when needed. For images, this means loading them only when they are about to enter the viewport. Modern browsers support the loading=”lazy” attribute; Intersection Observer can provide a flexible fallback.
JS: Lazy Loading Images
<!-- Native lazy loading -->
<img src="image.jpg" loading="lazy" alt="An image" width="200" height="200">
// Intersection Observer fallback
document.addEventListener("DOMContentLoaded", () => {
const lazyImages = [].slice.call(document.querySelectorAll("img.lazy"));
if ("IntersectionObserver" in window) {
const lazyImageObserver = new IntersectionObserver((entries, observer) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
const lazyImage = entry.target;
lazyImage.src = lazyImage.dataset.src;
lazyImage.classList.remove("lazy");
observer.unobserve(lazyImage);
}
});
});
lazyImages.forEach((image) => lazyImageObserver.observe(image));
}
});