图片懒加载
只加载视窗内的图片。需要判断图片当前是否在视窗范围内,判断方法:视窗高度+视窗下滑的高度>图片的offsetTop
ps:关于offsetTop、scrollTop、clientTop等一系列值的理解,这里贴一个网上的图片。
图片来源:https://www.jianshu.com/p/44abcc626318
对于图片来说,offsetTop是指该图片的顶端到上层(body)的顶端的距离。
// 实现图片懒加载
var num=document.getElementsByTagName('img').length
var img=document.getElementsByTagName('img')
var n=0//存储图片加载到的位置,避免每次都是从头遍历
var isLoadImg=false//当前窗口区的图片是否加载完成
var _clientHeight=document.documentElement.clientHeight//可视区高度
var _scrollTop=document.documentElement.scrollTop//滚动条距离顶部高度,卷曲出去的高度
// 监听窗口变化,重新计算可视区高度
function computedClientHeight(){
_clientHeight=document.documentElement.clientHeight
}
// 页面载入完毕,加载可视区内的图片
lazyload()
function lazyload(){
// 滚动条距离顶部高度
isLoadImg = n>=num //n<num说明还没有加载到
_scrollTop=document.documentElement.scrollTop||document.body.scrollTop || window.scrollY;
for(var i=n;i<num;i++){
if(img[i].offsetTop<_clientHeight + _scrollTop){
if(img[i].getAttribute('src')==''){
img[i].src=img[i].getAttribute('data-src')
console.log(img[i].offsetTop)
console.log(_clientHeight + _scrollTop)
}
n=i+1
}
}
// console.log(img)
}
// 防抖节流函数优化
function debounce(callback,delay){
let timer
return function(arg){
clearTimeout(timer)
timer=setTimeout(function(){
callback(arg)
},delay)
}
}
// 防抖--优化不断触发的窗口变化
window.addEventListener('resize',debounce(computedClientHeight,1000))
// 节流函数
function thro(func,wait,isLoad){
return function(){
// 形成闭包
if(!isLoad){
setTimeout(function(){
func()
isLoad=false
},wait)
}
}
}
// 节流--优化性能,一直拉 下拉条,100毫秒内只触发一次懒加载
window.addEventListener('scroll',thro(lazyload,100,isLoadImg))