How can I lazy load images inside #panel-scroll that has overflow: scroll; I tried this code sample but it gave me unexpected token error. Can anyone assist me with this?
document.addEventListener("DOMContentLoaded", function() {
var lazyImages = [].slice.call(document.querySelectorAll("img.lazy"));
if ("IntersectionObserver" in getElementById('#panel-scroll') {
let lazyImageObserver = new IntersectionObserver(function(entries, observer) {
entries.forEach(function(entry) {
if (entry.isIntersecting) {
let lazyImage = entry.target;
lazyImage.src = lazyImage.dataset.src;
lazyImage.srcset = lazyImage.dataset.srcset;
lazyImage.classList.remove("lazy");
lazyImageObserver.unobserve(lazyImage);
}
});
});
lazyImages.forEach(function(lazyImage) {
lazyImageObserver.observe(lazyImage);
});
} else {
// Possibly fall back to event handlers here
}
});
2
Answers
I’d consider the following updates:
getElementById
, you should use it without the ‘#’ symbol, as it is incorrect. It should be:IntersectionObserver
as an option:IntersectionObserver
with the #panel-scroll as the root.IntersectionObserver
.This script will efficiently load images only when they are near the viewport of your scrollable
#panel-scroll
div, enhancing performance and user experience.