Skip to content

Instantly share code, notes, and snippets.

@JoNilsson
Created March 22, 2024 21:12
Show Gist options
  • Save JoNilsson/89cc429f145d9e0ab458db7cc76d4799 to your computer and use it in GitHub Desktop.
Save JoNilsson/89cc429f145d9e0ab458db7cc76d4799 to your computer and use it in GitHub Desktop.
//-------------------------------------
// https://www.johannessnilsson.cc/blog/lazy-youtube
//-------------------------------------
// Apache License, Version 2.0
// Copyright (c) 2024 Johanness Nilsson
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// LazyYoutube.tsx
'use client'
import React,
{
useState,
useEffect,
useRef
}
from "react";
interface LazyYoutubeProps {
videoId: string
aspectRatio?: number
}
const LazyYoutube: React.FC<LazyYoutubeProps> = ({ videoId, aspectRatio = 16 / 9 }) => {
const [load, setLoad] = useState(false)
const videoRef = useRef<HTMLDivElement>(null)
useEffect(() => {
const observer = new IntersectionObserver((entries) => {
if (entries[0].isIntersecting) {
setLoad(true)
observer.disconnect()
}
})
if (videoRef.current) {
observer.observe(videoRef.current)
}
return () => {
if (videoRef.current) {
observer.unobserve(videoRef.current)
}
}
}, [])
return (
<div ref={videoRef} style={{ position: "relative", paddingTop: `${(1 / aspectRatio) * 100}%` }}>
{load ? (
<iframe
style={{ position: "absolute", top: 0, left: 0, width: "100%", height: "100%" }}
src={`https://www.youtube.com/embed/${videoId}`}
title="YouTube video player"
frameBorder="0"
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
allowFullScreen
></iframe>
) : null}
</div>
)
}
export default LazyYoutube
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment