一,什么是懒加载?
一般情况下,当一个页面加载以后,图片也会开始全部加载,这样会增加客户端和服务器的压力。为了减轻负担,让图片先出现在浏览器视口以后再进行加载。
方法一,使用三个相关API:
1,获取可视区域的高度 document.documentElement.clientHeight
2,获取元素到文档顶部的高度 element.offsetTop
3,获取浏览器窗口顶部与文档顶部之间的距 document.documentElement.scrollTop
var imgs = document.querySelectorAll('.lazyload-img');
//循环获取直到页面顶部的高度
function getElementTop(element) {
var actualTop = element.offsetTop;
var current = element.offsetParent;
while(current !== null) {
actualTop += current.offsetTop;
current = current.offsetParent;
}
return actualTop;
}
function lazyLoad(imgs) {
var vh = document.documentElement.clientHeight;
var st = document.documentElement.scrollTop || document.body.scrollTop;
imgs.forEach((item, index) => {
if (vh + st > getElementTop(imgs[index])) {
imgs[index].src = imgs[index].getAttribute('data-src');
}
});
}
window.onload = window.onscroll = function () {
lazyLoad(imgs);
}
方法二,使用一个相关API
getBoundingClientRect() //获取元素的大小及位置
{
bottom: 667.515625
height: 117.5
left: 269.046875
right: 489.9375
top: 550.015625
width: 220.890625
x: 269.046875
y: 550.015625
}
滚动条向下滚动的时候,bound.top值会越来越小,也就是图片到可视区顶部的距离也越来越小,所以当bound.top == clientHeight时,说明土片马上就要进入可视区了,即 bound.top<=clientHeight时,图片是在可视区域内的。
var imgs = document.querySelectorAll('.lazyload-img');
function lazyLoad() {
imgs.forEach(function(el){
var bound = el.getBoundingClientRect();
if(bound.top <= window.innerHeight){
console.log("el: ", el);
el.src = el.dataset.src;
}
})
}
window.onload = window.onscroll = function () {
lazyLoad();
}
修改时间 2021-07-02
声明:本站所有文章和图片,如无特殊说明,均为原创发布,转载请注明出处。