HTML:
<a href="chars/00004-538657410.png" data-fancybox>
<img class="lazy placeholder" data-src="chars/00004-538657410.png" class="w-100" />
</a>
JavaScript:
document.addEventListener("DOMContentLoaded", function () {
const lazyImages = document.querySelectorAll(".lazy");
if ("IntersectionObserver" in window) {
let lazyImageObserver = new IntersectionObserver(function (entries, observer) {
entries.forEach(function (entry) {
if (entry.isIntersecting) {
let lazyImage = entry.target;
lazyImage.src = lazyImage.dataset.src;
lazyImage.classList.remove("lazy");
lazyImage.classList.remove("placeholder");
lazyImageObserver.unobserve(lazyImage);
}
});
});
lazyImages.forEach(function (lazyImage) {
lazyImageObserver.observe(lazyImage);
});
} else {
// Fallback for browsers that don't support IntersectionObserver
let lazyLoadThrottleTimeout;
function lazyLoad() {
if (lazyLoadThrottleTimeout) {
clearTimeout(lazyLoadThrottleTimeout);
}
lazyLoadThrottleTimeout = setTimeout(function () {
let scrollTop = window.pageYOffset;
lazyImages.forEach(function (img) {
if (img.offsetTop < (window.innerHeight + scrollTop)) {
img.src = img.dataset.src;
img.classList.remove('lazy');
img.classList.remove('placeholder');
}
});
if (lazyImages.length == 0) {
document.removeEventListener("scroll", lazyLoad);
window.removeEventListener("resize", lazyLoad);
window.removeEventListener("orientationChange", lazyLoad);
}
}, 20);
}
document.addEventListener("scroll", lazyLoad);
window.addEventListener("resize", lazyLoad);
window.addEventListener("orientationChange", lazyLoad);
}
});