视频懒加载

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

在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>
相关推荐
2501_946230985 小时前
Cordova&OpenHarmony通知中心实现
android·javascript
南山安5 小时前
JavaScript 函数柯里化:从入门到实战,一文搞定(面试可用)
javascript·面试·函数式编程
谢尔登5 小时前
Monorepo 架构
前端·arcgis·架构
啃火龙果的兔子5 小时前
JavaScript 中的 Symbol 特性详解
开发语言·javascript·ecmascript
栀秋6665 小时前
你会先找行还是直接拍平?两种二分策略你Pick哪个?
前端·javascript·算法
漂流瓶jz5 小时前
PostCSS完全指南:功能/配置/插件/SourceMap/AST/插件开发/自定义语法
前端·javascript·css
xhxxx5 小时前
传统工具调用太痛苦?LangChain 一键打通 LLM 与真实世界
前端·langchain·llm
南山安6 小时前
LangChain学习:Memory实战——让你的大模型记住你
前端·javascript·langchain
BD_Marathon6 小时前
Promise基础语法
开发语言·前端·javascript
BOF_dcb7 小时前
网页设计DW
前端