<img loading="lazy" src="https://via.placeholder.com/320x200" alt="Lazy loaded image" />
lazy loading in html
<img src="myimage.jpg" loading="lazy" alt="..." />
<iframe src="content.html" loading="lazy"></iframe>
<img src="image.png" loading="lazy" alt="…" style="height:200px; width:200px;">
<img src="image.png" loading="lazy" alt="…" width="200" height="200">
<img src="path-to-image.png" loading="lazy" alt="something"/>
const imgTargets = document.querySelectorAll("img[data-src]");
const imgObserve = function (entries, observer) {
const [entry] = entries;
console.log(entry);
//replace src with data-src
if (!entry.isIntersecting) {
return;
}
entry.target.src = entry.target.dataset.src;
//load event
entry.target.addEventListener("load", function () {
entry.target.classList.remove("lazy-img");
});
observer.unobserve(entry.target);
};
const imgOptions = {
root: null,
threshold: 0,
rootMargin: "200px",
};
const imgObserver = new IntersectionObserver(imgObserve, imgOptions);
imgTargets.forEach(function (img) {
imgObserver.observe(img);
});