懒加载
当我们需要加载静态资源(比如图片)时,可以判断元素是否出现在可视区域,当即将出现时再加载,以此节省带宽
- 方法一:通过判断视口高度与元素距离文档顶部的高度和滚动条卷去的高度的差值,确定元素是否出现在可视区域
const box = document.querySelector('.box')
let clientHeight = document.documentElement.clientHeight
const offsetTop = box.offsetTop
addEventListener('scroll', () => {
let scrollTop = document.documentElement.scrollTop
if (offsetTop - scrollTop <= clientHeight) {
console.log('元素出现在可视区')
}
})
- 方法二:通过getBoundingClientRect API
const box = document.querySelector('.box')
let clientHeight = document.documentElement.clientHeight
addEventListener('scroll', () => {
const position = box.getBoundingClientRect()
let top = position.top
if (top <= clientHeight) {
console.log('元素出现在可视区')
}
})
const io = new IntersectionObserver(() => {
console.log('出现在可视区域')
})
io.observe(box)