视频懒加载

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

在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>
相关推荐
css趣多多3 小时前
组件没有原生事件
前端·javascript·vue.js
摘星编程3 小时前
React Native鸿蒙版:forwardRef组件引用转发
react native·react.js·harmonyos
IT陈图图3 小时前
Flutter × OpenHarmony 实战:优雅构建确认对话框的组件化方案
开发语言·javascript·flutter
雨季6663 小时前
Flutter 三端应用实战:OpenHarmony 简易文本末尾字符查看器开发指南
开发语言·javascript·flutter
小小弯_Shelby3 小时前
el-form表单简洁有效地解决新增与查看详情共用一个页面问题,控制el-form的disabled设置和修改样式
前端·vue.js·elementui
0思必得03 小时前
[Web自动化] 数据抓取、解析与存储
运维·前端·爬虫·selenium·自动化·web自动化
xiaoxue..4 小时前
全栈项目 学习日记 (第一章)
前端·react.js·面试·vite
chen_song_4 小时前
Agent 经典范式构建之 ReAct (Reasoning and Acting): 一种将“思考”和“行动”紧密结合的范式,让智能体边想边做,动态调整
前端·react.js·前端框架
想起你的日子4 小时前
CSS3 弹性盒子(Flex Box)
前端·css3
园小异4 小时前
2026年浏览器革命:Chrome Edge 人工智能版完全指南
前端·chrome