代码解释
懒加载也加延迟加载、按需加载,指在长网页中延迟加载图片数据,是一种较好的网页性能优化的方式。
优点
1. 减少了无用资源的加载
2. 提升用户体验
3. 防止加载过多图片而影响其他资源文件的加载
实现原理
方式一:浏览器原生API交叉观察者模式(IntersectionObserver)
IntersectionObserver 是一种浏览器提供的JavaScript API,用于监测元素与视窗的交叉状态。它能够告诉开发者一个元素是否进入或离开视窗,以及两者的交叉区域的大小和位置。
方式二:监听元素的 offsetTop 是否小于或等于浏览器可视区与已滚动距离之和
imgs.offsetTop<=window.innerHeight+document.body.scrollTop
window.innerHeight是浏览器可视区的高度
document.body.scrollTop || document.documentElement.scrollTop是浏览器滚动过的距离
imgs.offsetTop是元素顶部距离文档顶部的高度(包括了滚动条的距离)
代码实现
const DATA_SRC = 'data-src';
// IntersectionObserver 观察者模式
const observer = new IntersectionObserver((entries, observer) => {
entries.forEach(entry => {
if(entry.isIntersecting){
const img = entry.target;
img.setAttribute('src', img.getAttribute(DATA_SRC) ?? '')
observer.unobserve(img);
}
})
})
// 通过监听滚动事件
function scroll(el){
let clinetH = document.documentElement.clientHeight || window.innerHeight;
let scrollT = document.documentElement.scrollTop;
let offsetTop = el.offsetTop
if( offsetTop <= clinetH + scrollT ){
el.setAttribute('src', el.getAttribute(DATA_SRC) ?? '')
}
}
function lazyload(el, bilding){
el.getAttribute(DATA_SRC) ?? el.setAttribute(DATA_SRC, bilding.value)
'IntersectionObserver' in window ? observer.observe(el) : (window.addEventListener('load', () => scroll(el)), window.addEventListener('scroll', () => scroll(el)))
}
export { lazyLoad }
本文链接:https://blog.smallhao.fun/?id=5 转载需授权!
暂无评论
发表评论