I'm able to add the loading="lazy" attribute on individual images, or with JavaScript and apply them all at once.
But, when I do it with JavaScript, and then inspect the page, I see the images load on page load, but each image has the attribute attached.
Why does adding loading="lazy" with HTML load the image lazily, but adding the attrib with JavaScript doesn't provide the lazy loading behavior?
let img = document.querySelectorAll('img');
for (let i = 0; i < img.length; i++) {
let images = img[i];
images.setAttribute('loading', 'lazy');
}
img {
max-width: 100%;
height: auto;
}
.container {
margin-top: 2000px;
}
<div class="container">
<img src="https://images.unsplash.com/photo-1481349518771-20055b2a7b24">
<img src="https://images.unsplash.com/photo-1494253109108-2e30c049369b">
<img src="https://images.unsplash.com/photo-1494232410401-ad00d5433cfa">
</div>
srcattribute before it reaches the browser? if you changesrctodata-srcthe browser won't load it. Then you can add theloading="lazy"attribute and then change thesrcto the value ofdata-src.