一、scroll事件监听
<img src="default.jpg" data-src="http://www.xxx.com/target.jpg" />
let img = document.getElementsByTagName("img");
let num = img.length;
let count = 0;//计数器,从第一张图片开始计
lazyload();//首次加载别忘了显示图片
window.addEventListener('scroll', throttle(lazyload, 300));//节流
function lazyload() {
let viewHeight = document.documentElement.clientHeight;//视口高度
let scrollHeight = document.documentElement.scrollTop ||
document.body.scrollTop;//滚动条卷去的高度
for(let i = count; i <num; i++) {
// 元素现在已经出现在视口中
if(img[i].offsetTop < scrollHeight + viewHeight) {
if(img[i].getAttribute("src") !== "default.jpg") continue;
img[i].src = img[i].getAttribute("data-src");
count ++;
}
}
}
二、getBoundingClientRect
function lazyload() {
for(let i = count; i <num; i++) {
// 元素现在已经出现在视口中
if(img[i].getBoundingClientRect().top <
document.documentElement.clientHeight) {
if(img[i].getAttribute("src") !== "default.jpg") continue;
img[i].src = img[i].getAttribute("data-src");
count ++;
}
}
}
三、IntersectionObserver
let img = document.getElementsByTagName("img");
const observer = new IntersectionObserver(changes => {
//changes 是被观察的元素集合
for(let i = 0, len = changes.length; i < len; i++) {
let change = changes[i];
// 通过这个属性判断是否在视口中
if(change.isIntersecting) {
const imgElement = change.target;
imgElement.src = imgElement.getAttribute("data-src");
observer.unobserve(imgElement);
}
}
})
Array.from(img).forEach(item => observer.observe(item));
文章介绍了三种图片懒加载的方法:使用scroll事件监听,通过getBoundingClientRect计算元素位置,以及利用IntersectionObserver接口。这些技术旨在优化网页性能,当图片进入视口时才加载,提高页面加载速度。
1364

被折叠的 条评论
为什么被折叠?



