Problem Overview
Lazy loading is a design pattern that postpones loading non-essential resources at the point the page is initially rendered. This can significantly improve the performance of your web applications. Here’s how to implement lazy loading for images:
- Use the Loading Attribute: The simplest way to implement lazy loading is by using the
loading="lazy"
attribute in your<img>
tags. For example:
<img src="image.jpg" loading="lazy" alt="Description of image">
const images = document.querySelectorAll('img[data-src]');
const config = { rootMargin: '0px 0px 200px 0px' };
let observer;
if ('IntersectionObserver' in window) {
observer = new IntersectionObserver((entries, observer) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const img = entry.target;
img.src = img.dataset.src;
img.classList.remove('lazy');
observer.unobserve(img);
}
});
}, config);
images.forEach(image => {
observer.observe(image);
});
}
By using these techniques, you can enhance your web application’s loading performance and improve user experience.