在聲明img元素時(shí),只需要將其圖片地址放到data-src中,并且聲明class="lazyload"即可實(shí)現(xiàn)圖片的懶加載效果。
示例:
<img data-src="https://xxxxxx.com?sjdijsa" class="lazyload">
<img data-src="https://xxxxxx.com?sjdijsa" class="lazyload">
調(diào)用lazyload函數(shù),并傳入?yún)?shù)。
- 第一個(gè)參數(shù)表示所有的img標(biāo)簽,可以根據(jù)具體的元素進(jìn)行調(diào)整
- 第二個(gè)參數(shù)表示圖片距離視口多少距離
lazyload(document.querySelectorAll('img'),0)
以下為實(shí)現(xiàn)的源碼。
具體思路:每次觸發(fā)scroll事件時(shí)(節(jié)流),找到所有含有class為lazyload的img標(biāo)簽。遍歷所有標(biāo)簽,判斷是否符合加載的要求,完成渲染。
lazyload(document.querySelectorAll('img'),0)
function lazyload(images,distance){
imgs = Array.from(images)
if('IntersectionObserver' in window){
let observer = new IntersectionObserver(function(entries){
entries.forEach(entry=>{
loadImage(entry.target,()=>{
observer.unobserve(entry.target)
})
})
},{threshold: 0.01})
imgs.forEach(img=>observer.observe(img))
}else{
document.onscroll = throttle(function(){
imgs = imgs.filter(img=>img.classList.contains('lazyload'))
imgs.forEach(img=>{
if(imgView(img,distance)){
loadImage(img)
}
})
},200)
document.dispatchEvent(new Event('scroll'))
}
function throttle(fn,wait){
let lastTime = null
let nowTime = null
return function(){
nowTime = new Date()
if(!lastTime || nowTime - lastTime > wait){
fn.apply(this,arguments)
lastTime = nowTime
}
}
}
function imgView(img,distance){
let { top } = img.getBoundingClientRect()
let viewHeight = document.documentElement.clientHeight
return top>0 && top<viewHeight+distance
}
function loadImage(img,callback){
let image = new Image()
image.src = img.dataset.src
image.onload = function(){
img.src = image.src
img.classList.remove('lazyload')
callback()
}
}
}