视频懒加载

31 篇文章 1 订阅
5 篇文章 0 订阅

有一个视频自动播放的需求,但是需要懒加载,避免阻塞页面渲染

在useEffect里面加入IntersectionObserver

IntersectionObserver 接口(从属于 Intersection Observer API)提供了一种异步观察目标元素与其祖先元素或顶级文档视口(viewport)交叉状态的方法。其祖先元素或视口被称为根(root)。

当一个 IntersectionObserver 对象被创建时,其被配置为监听根中一段给定比例的可见区域。一旦 IntersectionObserver 被创建,则无法更改其配置,所以一个给定的观察者对象只能用来监听可见区域的特定变化值;然而,你可以在同一个观察者对象中配置监听多个目标元素。

 const videoRef = useRef<any>(null)
useEffect(() => {
    if (!('IntersectionObserver' in window)) {
      // If IntersectionObserver is not supported, load the video immediately
      if (videoRef.current && appConfig?.videoUrl) {
        videoRef.current.play()
      }
      return
    }

    const observer = new IntersectionObserver((entries) => {
      entries.forEach((entry) => {
        if (entry.isIntersecting) {
          if (videoRef.current && appConfig?.videoUrl) {
            videoRef.current.play()
          }
          observer.unobserve(videoRef.current)
        }
      })
    })
    if (videoRef.current) {
      observer.observe(videoRef.current)
    }
    return () => {
      if (videoRef.current) {
        observer.unobserve(videoRef.current)
      }
    }
  }, [appConfig?.videoUrl, videoRef.current])

<video
            ref={videoRef}
            id="my-video"
            className="video-js w-full"
            loop
            // controls={false}
            preload="auto"
            width="100%"
            height="264"
            poster="https://dhh/dhjfh/ddd.jpg"
            data-setup="{}"
          >
            <source src={videoUrl} type="video/mp4" />
            <p className="vjs-no-js">
              To view this video please enable JavaScript, and consider
              upgrading to a web browser that
              <a
                href="https://videojs.com/html5-video-support/"
                target="_blank"
              >
                supports HTML5 video
              </a>
            </p>
          </video>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值