From 6829c6e525494c27a5e60509cf78c9f6223b8f47 Mon Sep 17 00:00:00 2001 From: wibus-wee <1596355173@qq.com> Date: Sun, 19 May 2024 10:32:26 +0800 Subject: [PATCH] fix: simultaneous loading causes page blocking --- components/Video/index.tsx | 50 +++++++++++++++++++++----------------- 1 file changed, 28 insertions(+), 22 deletions(-) diff --git a/components/Video/index.tsx b/components/Video/index.tsx index bb66f081..70d2f6fb 100644 --- a/components/Video/index.tsx +++ b/components/Video/index.tsx @@ -1,33 +1,41 @@ import { useEffect, useRef } from 'react'; +const observerOptions = { + root: null, + rootMargin: '0px', + threshold: 0.5, +}; + export default function Video({ src }) { const videoRef = useRef(null); + const observerRef = useRef(null); useEffect(() => { - const options = { - root: null, - rootMargin: '0px', - threshold: 0.5, - }; - - const handleIntersection = (entries) => { - entries.forEach((entry) => { - if (entry.isIntersecting) { - videoRef.current.play(); - } else { - videoRef.current.pause(); - } - }); - }; - - const observer = new IntersectionObserver(handleIntersection, options); - observer.observe(videoRef.current); + observerRef.current = new IntersectionObserver(handleIntersection, observerOptions); + if (videoRef.current) { + observerRef.current.observe(videoRef.current); + } return () => { - videoRef.current && observer.unobserve(videoRef.current); + if (videoRef.current && observerRef.current) { + observerRef.current.unobserve(videoRef.current); + } }; }, [src]); + const handleIntersection = (entries: IntersectionObserverEntry[]) => { + entries.forEach((entry: IntersectionObserverEntry) => { + if (entry.isIntersecting) { + if (!videoRef.current.src) { + videoRef.current.src = src; + } + videoRef.current.play(); + } else { + videoRef.current.pause(); + } + }); + }; + return ( + /> ); }