当前位置:网站首页>图片懒加载IntersectionObserver
图片懒加载IntersectionObserver
2022-08-11 11:52:00 【-加油】
1、getBoundingClientRect
//获取图片元素
const images = document.querySelectorAll('img');
//scroll滚动事件
window.addEventListener('scroll',(e)=>{
//判断每张图片的位置是否出现在可视区域
images.forEach(image =>{
//获取每张图片到顶部的距离
const imTop = image.getBoundingClientRect().top;
//距离小于窗口显示区的高度 : 能够显示出来 可以加载
if(imTop<window.innerHeight){
//使用自定义属性data-src。在定义的时候:<img data-src="图片资源路径" >
const data_src = image.getAttribute('data-src');//获取自定义属性
image.setAttribute('src',data_src);//赋值给原本的的src属性,这样就显示了
};
//即使图片加载了还是会不断触发事件,非常消耗资源
console.log("触发");
})
})
优化:使用浏览器提供的构造函数IntersectionObserver。
//获取图片元素
const images = document.querySelectorAll('img');
//定义callback函数 接受的参数是数组
const callback =(entries)=>{
entries.forEach(entry=>{
//isIntersecting属性为true时,说明到可视区域了 可以显示出来
if(entry.isIntersecting){
//target属性 就是目标元素
const image = entry.target;
const data_src = image.getAttribute('data-src')
image.setAttribute('src',data_src);
//显示出来后取消 观察 这个动作。不再观察了
obser.unobserve(image);
console.log('触发');
}
})
}
//回调函数callback一般触发两次 ,目标元素能看见 触发一次,目标元素看不见了 触发一次
const obser = new IntersectionObserver(callback);
images.forEach(image =>{
//xxx.observe(DOM节点) 观察每个img节点
obser.observe(image);
})
边栏推荐
猜你喜欢
随机推荐
Mybaits学习笔记(四)动态Sql
老生常谈:面试必问“三次握手,四次挥手”这么讲,保证你忘不了
pip安装后仍有ImportError No module named XX问题解决
初始化块(父类优先于子类)
MySQL --- storage engine
同城是美团电商的解法吗?
eyb:Redis集成菜单到权限组菜单更新功能(二)
【集创赛】arm杯一等奖作品:智能BLDC驱动系统
路测数据合并
【剑指offer-牛客网刷题】第一篇-斐波拉契数列-C实现
04-JS作用域及常用数据类型(对象、数组、字符串、数字、时间)
From Douyin to Volcano Engine——Seeing the Evolution and Opportunities of Streaming Media Technology
img图片加载错误时显示默认图片
二叉树详解
Uber的20万容器实践:如何避免容器化环境中的 CPU 节流
Through the thermal lens focus on different types of gaussian model
概率期望及计数的一些性质应用
Web3 创业者指南:如何为你的产品构建一个去中心化社区?
03-JS条件分支及循环
怎么了