Skip to content
This repository has been archived by the owner on Nov 2, 2024. It is now read-only.

Commit

Permalink
fix: simultaneous loading causes page blocking
Browse files Browse the repository at this point in the history
  • Loading branch information
wibus-wee committed May 19, 2024
1 parent dbd574c commit 6829c6e
Showing 1 changed file with 28 additions and 22 deletions.
50 changes: 28 additions & 22 deletions components/Video/index.tsx
Original file line number Diff line number Diff line change
@@ -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 (
<video
ref={videoRef}
Expand All @@ -37,8 +45,6 @@ export default function Video({ src }) {
loop
controls
className="mt-6 rounded-xl border dark:border-zinc-800"
>
<source src={src} type="video/mp4" />
</video>
/>
);
}

0 comments on commit 6829c6e

Please sign in to comment.