Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Lazy video bg
import React, { useEffect, useRef } from 'react'
import videoAV1 from '../../../static/video/video.av1.mp4'
import videoH264 from '../../../static/video/video.h264.mp4'
import styles from './VideoBackground.module.css'
function VideoBackground() {
const videoRef = useRef<HTMLVideoElement | null>(null)
const videoSrcAV1ref = useRef<HTMLSourceElement | null>(null)
const videoSrcH264ref = useRef<HTMLSourceElement | null>(null)
const videoPlaceholderRef = useRef<HTMLDivElement | null>(null)
useEffect(function lazyLoadVideo() {
const connection =
window.navigator.connection ||
window.navigator.mozConnection ||
window.navigator.webkitConnection
if (connection && (connection.type === 'cellular' || connection.saveData)) {
return undefined
}
if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) {
return undefined
}
function hideVideoPlaceholder() {
if (videoPlaceholderRef.current) {
videoPlaceholderRef.current.style.display = 'none'
}
}
if (videoRef.current) {
videoRef.current.addEventListener('loadeddata', hideVideoPlaceholder)
}
const timeout = setTimeout(() => {
if (
videoSrcAV1ref.current &&
videoSrcH264ref.current &&
videoRef.current
) {
videoSrcAV1ref.current.src = videoAV1
videoSrcH264ref.current.src = videoH264
videoRef.current.load()
}
}, 500)
return () => {
clearTimeout(timeout)
if (videoRef.current) {
videoRef.current.removeEventListener('loadeddata', hideVideoPlaceholder)
}
}
}, [])
return (
<div className={styles.root}>
<video
ref={videoRef}
autoPlay
muted
loop
playsInline
className={styles.video}>
<source ref={videoSrcAV1ref} type="video/mp4; codecs=av01.0.05M.08" />
<source ref={videoSrcH264ref} type="video/mp4" />
</video>
<div className={styles.placeholder} ref={videoPlaceholderRef} />
</div>
)
}
export { VideoBackground }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment