我正试图找到一种在我的网站上延迟加载图像的方法,因为我会有一个很大的图像库,所以我不想有任何性能问题。我在网上学习教程,用数据src替换src,但这给我留下了一个断开的链接。如果我集成了一个lightgallery,有可能进行这样的懒惰加载吗?
document.addEventListener("DOMContentLoaded", function() {
var lazyloadImages = document.querySelectorAll("img.lazy");
var lazyloadThrottleTimeout;
function lazyload() {
if (lazyloadThrottleTimeout) {
clearTimeout(lazyloadThrottleTimeout);
}
lazyloadThrottleTimeout = setTimeout(function() {
var scrollTop = window.pageYOffset;
lazyloadImages.forEach(function(img) {
if (img.offsetTop < (window.innerHeight + scrollTop)) {
img.src = img.dataset.src;
img.classList.remove('lazy');
}
});
if (lazyloadImages.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);
});
<div class="row gallery-container" id="lightgallery">
<div class="col-sm-6 col-md-4 col-lg-4 col-xl-3 item img-gallery center-images-tattoo image-box" data-aos="fade" data-src="images/tattoo/IMG_1086.jpg" data-sub-html="<h4>Fading Light</h4><p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dolor doloremque hic excepturi fugit, sunt impedit fuga tempora, ad amet aliquid?</p>">
<a href="#"><img data-src="images/tattoo/IMG_1086.jpg" alt="Tattoo-image" class="img-fluid img-resize2 lazy"></a>
</div>
<div class="col-sm-6 col-md-4 col-lg-4 col-xl-3 item img-gallery center-images-tattoo image-box" data-aos="fade" data-src="images/tattoo/IMG_1089.jpg" data-sub-html="<h4>Fading Light</h4><p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laboriosam omnis quaerat molestiae, praesentium. Ipsam, reiciendis. Aut molestiae animi earum laudantium.</p>">
<a href="#"><img data-src="images/tattoo/IMG_1089.jpg" alt="Tattoo-image" class="img-fluid img-resize2 lazy"></a>
</div>
<div class="col-sm-6 col-md-4 col-lg-4 col-xl-3 item img-gallery center-images-tattoo image-box" data-aos="fade" data-src="images/tattoo/IMG_1090.jpg" data-sub-html="<h4>Fading Light</h4><p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quidem reiciendis, dolorum illo temporibus culpa eaque dolore rerum quod voluptate doloribus.</p>">
<a href="#"><img data-src="images/tattoo/IMG_1090.jpg" alt="Tattoo-image" class="img-fluid img-resize2 lazy"></a>
</div>
用CSS从DOM中隐藏未加载的图像怎么样?
img.lazy {
display: none;
}