Ask any question about Web Development here... and get an instant response.
Post this Question & Answer:
How can I implement lazy loading for images using native HTML and JavaScript?
Asked on Apr 29, 2026
Answer
Lazy loading images is a technique to improve page performance by deferring the loading of images until they are needed. This can be achieved using the `loading` attribute in HTML or by using JavaScript with the Intersection Observer API. Here's how you can implement it:
<!-- BEGIN COPY / PASTE -->
<!-- Using the native loading attribute -->
<img src="image.jpg" alt="Description" loading="lazy">
<!-- Using Intersection Observer API -->
<script>
document.addEventListener("DOMContentLoaded", function() {
const images = document.querySelectorAll('img[data-src]');
const config = {
rootMargin: '0px 0px 200px 0px',
threshold: 0
};
let observer = new IntersectionObserver(function(entries, self) {
entries.forEach(entry => {
if (entry.isIntersecting) {
let 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 a more customizable approach and can be used for browsers that do not support the `loading` attribute.
- 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 optimal performance.
Recommended Links:
