javascript - 增加延迟加载检测的视口
问题描述
我正在使用这个脚本来延迟加载标签,我对其中的大部分内容都很熟悉,但有一个部分我不太确定
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>
如果它进入视口的底部,它将加载一个。我希望它提前加载 imgs,比如在视口下方 200 像素 - 300 像素,这样用户就不会看到加载的发生。
我认为这与这部分有关
if(img.offsetTop < (window.innerHeight + scrollTop))
我不知道这些值是什么意思,所以我不确定如何指定提前 200px 开始延迟加载。
干杯
解决方案
试试这个:
if(img.offsetTop < (window.innerHeight + scrollTop + 250))
推荐阅读
- c# - 使用 XUnit 测试内部方法引发空引用异常
- android - 使用 MaterialComponents 和 BottomNavigationView 的奇怪行为。安卓
- mongodb - 无法再连接到 mongoDB Atlas
- node.js - 无法创建 cookie-Node.js
- python - 查找匹配时通过创建新列来分配新单词
- java - 如何使用 CipherInputStream 解密文件或为什么以下方法不起作用
- javascript - 邮政编码的复杂正则表达式模式
- json - 在“del”内的“select”中使用带有“contains”的 jq 不起作用
- python - openpyxl:使用 COUNTIF 有条件地格式化
- angular - TypeError:无法使用 spyOn 读取未定义的属性“订阅”