我正在使用这个脚本来延迟加载标签,我对其中的大部分内容都很熟悉,但有一部分我不太确定
document.addEventListener("DOMContentLoaded", function() {
var lazyloadImages;
if ("IntersectionObserver" in window) {
lazyloadImages = document.querySelectorAll(".lazy");
var imageObserver = new IntersectionObserver(function(entries, observer) {
entries.forEach(function(entry) {
if (entry.isIntersecting) {
var image = entry.target;
image.src = image.dataset.src;
image.classList.remove("lazy");
imageObserver.unobserve(image);
}
});
});
lazyloadImages.forEach(function(image) {
imageObserver.observe(image);
});
} else {
var lazyloadThrottleTimeout;
lazyloadImages = document.querySelectorAll(".lazy");
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);
}
})
目前它将加载 <img>
如果它进入视口(viewport)的底部。我更喜欢它提前加载 img,比如在视口(viewport)下方 200px - 300px 处,这样用户就看不到加载的发生。
我认为这与这部分有关
if(img.offsetTop < (window.innerHeight + scrollTop))
我不知道这些值是什么意思,所以我不确定如何指定提前 200 像素开始延迟加载。
干杯
最佳答案
试试这个:
if(img.offsetTop < (window.innerHeight + scrollTop + 250))
关于javascript - 增加延迟加载检测的视口(viewport),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56435588/