用data-src自定义属性,让浏览器暂不加载图片
html
<img data-src='./img1.png'/>
<img data-src='./img2.png'/>
<img data-src='./img3.png'/>
js
const images = document.querySelectAll('img');
const callback = entries =>{
entries.forEach( entry =>{
if(entry.isIntersecting){
const image = entry.target
const data_src = image.getAttrbute('data-src')
img.setAttribute('src',data_src);
// 结束观察 防止触发多次
observer.unobserve( image );
console.log('触发')
}
})
}
const observe = new IntersectionObserver(callback);
images.forEach( image =>{
//开启观察模式
observe.observe(image)
})