Created
October 17, 2019 10:06
-
-
Save smashercosmo/31be5175144acfec3de12d39283dfce2 to your computer and use it in GitHub Desktop.
Lazy video bg
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
| 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