Ask any question about Web Development here... and get an instant response.
Post this Question & Answer:
How can I implement lazy loading for images to improve page performance? Pending Review
Asked on May 20, 2026
Answer
Lazy loading images is a technique to defer the loading of images until they are about to enter the viewport, which improves page performance by reducing initial load time and bandwidth usage. This can be achieved using the `loading` attribute in HTML or JavaScript Intersection Observer API for more control.
<!-- BEGIN COPY / PASTE -->
<!-- Using the loading attribute -->
<img src="image.jpg" alt="Description" loading="lazy">
<!-- Using Intersection Observer -->
<script>
document.addEventListener("DOMContentLoaded", function() {
const images = document.querySelectorAll('img[data-src]');
const config = { rootMargin: '0px 0px 50px 0px', threshold: 0.01 };
let observer = new IntersectionObserver((entries, self) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const img = entry.target;
img.src = img.dataset.src;
self.unobserve(img);
}
});
}, config);
images.forEach(image => observer.observe(image));
});
</script>
<!-- END COPY / PASTE -->Additional Comment:
- The `loading="lazy"` attribute is supported in most modern browsers and is the simplest way to implement lazy loading.
- The Intersection Observer API provides more flexibility and can be used for other lazy loading tasks beyond images.
- Ensure that images have a placeholder or a defined size to prevent layout shifts as they load.
- Test lazy loading implementation across different devices and network conditions to ensure smooth performance.
Recommended Links:
