视频懒加载

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

在useEffect里面加入IntersectionObserver

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

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

js 复制代码
 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>
相关推荐
金梦人生1 天前
UniApp + Vue3 + TS 工程化实战笔记
前端·微信小程序
海云前端11 天前
20 个浏览器原生能力 替代工具库少写百行代码
前端
Holin_浩霖1 天前
🌿 Fiber 异步渲染机制 & 时间切片原理详解
前端
烟袅1 天前
深入浏览器渲染流程:从 HTML/CSS/JS 到 60FPS 的视觉魔法
前端·css·html
有点笨的蛋1 天前
JavaScript 执行机制深度解析:编译、执行上下文、变量提升、TDZ 与内存模型
前端·javascript
jump6801 天前
ts的范性
前端
_一两风1 天前
深入理解JavaScript执行机制:从一道经典面试题说起
javascript
阿凡达蘑菇灯1 天前
langgraph---条件边
开发语言·前端·javascript
San301 天前
深入理解浏览器渲染流程:从HTML/CSS到像素的奇妙旅程
javascript·css·html
海云前端11 天前
别再堆 if-else 了!TypeScript 模式匹配让代码更优雅
前端