第一种,可视区域高度对比
通过获取可视区域的高度,document.ducoumentElement.clientHeight,和当前Image元素的
const bufferHeight = 600;
const clientHeight = document.documentElement.clientHeight;
const isInVisible = (imgNode)=>{
const imgRect = imgNode.getBoundingClientRect();
return imgRect.top > clientHeight && imgRect.top - bufferHeight < clientHeight&& !imgNode.getAttribute("src");
};
let isFinished = true;
imagesNode.forEach((imgNode) => {
if(!imgNode.getAttribute("src")) {
isFinished = false;
}
if(isInVisible(imgNode)) {
imgNode.setAttribute("src", imgNode.dataset.src);
}
});
if(isFinished) {
document.removeEventListener("scroll",loadInvisibleImg);
}
第二种,intersectionObserver
var imageObserver = new IntersectionObserver(function(entries, observer) {
entries.forEach(function(entry) {
// 图片是否进入视窗
if (entry.isIntersecting) {
var image = entry.target;
image.src = image.dataset.src;
imageObserver.unobserve(image);
}
});
});
// 将观察者注册到所有图片上
imagesNode.forEach(function(image) {
imageObserver.observe(image);
});