IntersectionObserver与元素可见性

场景

页面上控件的嵌套层级较深的情况下, 如果一次全部渲染出来, 会导致页面卡顿. 而此时需要懒加载.

懒加载的定义

视窗之外的控件不加载, 等当前控件滚动到视窗内后, 再进行加载.

如何判定控件在视窗范围内

使用IntersectionObserver

IntersectionObserver原理

(PS: 以下内容搬自MDN)
提供了一种异步观察目标元素与其祖先元素或顶级文档视窗(viewport)交叉状态的方法。祖先元素与视窗(viewport)被称为根(root)。

参数

IntersectionObserver有两个参数, callbackoptions
callback,顾名思义就是该API的回调, 用于处理自己的业务逻辑. 该回调也接收一个参数: entries, 该参数是一个数组, 会将监听的所有DOM, 经过包装后, 形成一个API, 这里面有几个常用的参数.
下面给出TS的定义


interface DomRect {
    width: Number,
    height: Number,
    left: Number,
    top: Number,
    bottom: Number,
    right: Number,
    y: Number,
    x: Number,
}

const intersectionRatioSize = <const>[0, 1]

interface IntersectionObserverEntry {
    boundingClientRect: DomRect,
    // 取值在0 - 1之间, 0即不可见, 1是可见
    intersectionRatio: intersectionRatioSize[number],
    // 交叉的一瞬间, 当前被观测DOM, 在视窗内的大小
    intersectionRect: DomRect,
    isIntersecting: Boolean,
    isVisible: Boolean,
    rootBounds: DomRect,
    target: HTMLElement,
    // 触发回调时,距离当前页面初始打开时的时间间隔, 单位是毫秒(ms)
    time: Number
}

interface Options {
    threshold: Number [],
    rootMargin: String,
    delay: number,
    trackVisibility: Boolean,
    root: HTMLElement
}

type callback = (entry: IntersectionObserverEntry [], options?: any )=>void(null)

如何使用

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>IntersectionObserver</title>
</head>
<style>
    * {
        margin: 0;
        padding: 0;
        margin: 0;
        width: 100%;
        height: 100%;
    }
    #div {
        width: 200px;
        height: 200px;
        background-color: blueviolet;
        margin-left: 1000px;
        margin-top: 900px;
    }
</style>
<body>
    <div id="div"></div>
</body>
<script>

  const div = document.getElementById('div')
  const options = {
    threshold: [0.000001],
    rootMargin: '-5px 0px 0px 0px',
    delay: 300,
    trackVisibility: true
  }
  let prevIntersectionRatio = 1
  const callback = (entries, p2) => {
    // 最多接收两个参数, 第二个参数是配置信息Options
    console.log(entries, p2)
    entries.forEach(entry => {
      if (entry.intersectionRatio === prevIntersectionRatio) {
        return
      }
      // 如果当前的entry.intersectionRatio为1,表示可见; 为0不可见
      prevIntersectionRatio = entry.intersectionRatio
      // 下面是业务代码
    })
  }
  const observer = new window.IntersectionObserver(callback, options)
  observer.observe(div)
</script>
</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值