图片懒加载其实就是延迟加载
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<p>图片懒加载</p>
<p>图片懒加载</p>
<p>图片懒加载</p>
<p>图片懒加载</p>
<p>图片懒加载</p>
<p>图片懒加载</p>
<p>图片懒加载</p>
<p>图片懒加载</p>
<p>图片懒加载</p>
<p>图片懒加载</p>
<p>图片懒加载</p>
<p>图片懒加载</p>
<p>图片懒加载</p>
<p>图片懒加载</p>
<p>图片懒加载</p>
<p>图片懒加载</p>
<p>图片懒加载</p>
<p>图片懒加载</p>
<p>图片懒加载</p>
<p>图片懒加载</p>
<p>图片懒加载</p>
<p>图片懒加载</p>
<p>图片懒加载</p>
<p>图片懒加载</p>
<p>图片懒加载</p>
<p>图片懒加载</p>
<img data-src="./金城武.jpg">
<p>图片懒加载</p>
<p>图片懒加载</p>
<p>图片懒加载</p>
<p>图片懒加载</p>
<p>图片懒加载</p>
<script>
const images = document.querySelectorAll('img')
// 方法一:
// window.addEventListener('scroll', e => {
// images.forEach(image => {
// let imageTop = image.getBoundingClientRect().top
// if (imageTop <= window.innerHeight) {
// const data_src = image.getAttribute('data-src')
// image.setAttribute('src', data_src)
// }
// })
// })
//方法二:
const callback = (entries) => {
entries.forEach(entry => {
console.log(entry)
if (entry.isIntersecting) {
const image = entry.target
const data_src = image.getAttribute('data-src')
image.setAttribute('src', data_src)
observer.unobserve(image)
}
})
}
const observer = new IntersectionObserver(callback)
images.forEach(image => {
observer.observe(image)
})
</script>
</body>
</html>
方法一和方法二都是需要data-**属性
方法一
监听scroll事件
需要知道两个高度
窗口显示区的高度:window.innerHeight
图片到视窗上边的距离(高度):getBoundingClientRect().top
方法二:
IntersectionObserver 交叉观察着模式
本质是浏览器内置的一个构造函数
var observer = new IntersectionObserver(callback,options);
IntersectionObserver
支持两个参数:
callback
是当被监听元素的可见性变化时,触发的回调函数
options
是一个配置参数,可选,有默认的属性值
var observer = new IntersectionObserver(changes => {
for (const change of changes) {
console.log(change.time);
// Timestamp when the change occurred
// 当可视状态变化时,状态发送改变的时间戳
// 对比时间为,实例化的时间,
// 比如,值为1000时,表示在IntersectionObserver实例化的1秒钟之后,触发该元素的可视性变化
console.log(change.rootBounds);
// Unclipped area of root
// 根元素的矩形区域信息,即为getBoundingClientRect方法返回的值
console.log(change.boundingClientRect);
// target.boundingClientRect()
// 目标元素的矩形区域的信息
console.log(change.intersectionRect);
// boundingClientRect, clipped by its containing block ancestors,
// and intersected with rootBounds
// 目标元素与视口(或根元素)的交叉区域的信息
console.log(change.intersectionRatio);
// Ratio of intersectionRect area to boundingClientRect area
// 目标元素的可见比例,即intersectionRect占boundingClientRect的比例,
// 完全可见时为1,完全不可见时小于等于0
console.log(change.target);
// the Element target
// 被观察的目标元素,是一个 DOM 节点对象
// 当前可视区域正在变化的元素
}
}, {});
// Watch for intersection events on a specific target Element.
// 对元素target添加监听,当target元素变化时,就会触发上述的回调
observer.observe(target);
// Stop watching for intersection events on a specific target Element.
// 移除一个监听,移除之后,target元素的可视区域变化,将不再触发前面的回调函数
observer.unobserve(target);
// Stop observing threshold events on all target elements.
// 停止所有的监听
observer.disconnect();