Created
May 21, 2025 15:17
-
-
Save Muzammil-cyber/0be770fd468d89bf2179df1c4a358c81 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"use client"; | |
import { KeyTextField } from "@prismicio/client"; | |
import { useEffect, useRef, useState } from "react"; | |
type VideoProps = { | |
youTubeID: KeyTextField; | |
}; | |
export function LazyYouTubePlayer({ youTubeID }: VideoProps) { | |
const [isInView, setIsInView] = useState(false); | |
const containerRef = useRef<HTMLDivElement>(null); | |
useEffect(() => { | |
const currentContainerRef = containerRef.current; | |
const observer = new IntersectionObserver( | |
([entry]) => { | |
if (entry.isIntersecting) { | |
setIsInView(true); | |
} | |
}, | |
{ threshold: 0, rootMargin: "1500px" } // change the rootmarign value to choose how early you want to load (0 to load in in screen) | |
); | |
if (currentContainerRef) { | |
observer.observe(currentContainerRef); | |
} | |
return () => { | |
if (currentContainerRef) { | |
observer.unobserve(currentContainerRef); | |
} | |
}; | |
}); | |
return ( | |
<div className="relative h-full w-full" ref={containerRef}> | |
{isInView && ( | |
<iframe | |
src={`https://www.youtube-nocookie.com/embed/${youTubeID}?autoplay=1&mute=1&loop=1&playlist=${youTubeID}`} | |
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" | |
className="pointer-events-none h-full w-full border-0" | |
/> | |
)} | |
</div> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment