视频懒加载

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

在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>
相关推荐
excel1 小时前
Marked 与 Markdown 有什么区别?该怎么选?
前端
Da Da 泓2 小时前
五子棋 Web 端测试用例报告
前端·网络·websocket·网络协议·测试用例·项目
小豆庄2 小时前
视频敏感信息脱敏:本地推理与云端API的工程取舍
阿里云·ai·视频·纹理贴图
zxcvb1533 小时前
远程查看本地文档:一条轻量 Web 文件服务的工程化链路
前端·远程查看文档
niucloud-admin3 小时前
NIUCLOUD PHP SAAS上门家政使用文档:城市管理
java·前端·php
程序员大阳3 小时前
副队长JavaScript教程(50)-DOM:网页开发的起点
javascript·dom·es·节点·概念·document·关系
北岛贰3 小时前
啵啵音乐迎来全新升级!
前端
hkNaruto5 小时前
【AI】基于大模型的AI游戏地图生成、控制方案:AI Native Game Harness 迁移操作手册
前端·人工智能·游戏
IT_陈寒5 小时前
Java序列化踩坑记:对象循环引用让我加班两小时
前端·人工智能·后端
Acro6 小时前
快给macOS 上的Grok Bot换一套皮肤
前端