Lazy Loading Videos in a React App: Playing Only When in Viewport

––– views

1 min read

Working with video can be troublesome, I recently had a task to implement a Video on the home page hero area, which would play immediately, won't affect performance, would stop playing when it goes out of the screen and will restart if the user scrolls back up. ⁠ ⁠Talk about specific demands from a client.⁠

⁠Anyway I started researching, and decided to go with the native HTML way, I did experience a couple of problems along the way, especially with the mobile version of it, but in the end, I managed to reach the client's demands.

playsInline is the property that finally got it to autoplay on IOS

HTML video.jsx

<video
className="full-width-video"
ref={videoRef}
playsInline
autoPlay
muted
webkit-playsinline="true"
preload="auto"
type='video/mp4'
>
<source src="./hero-video.mp4" type="video/mp4" />
</video>

The video was less than 500kb so it wasn't affecting performance on mobile at all, depending on the time you're reading this you may be able to check the final result here. ⁠⁠For the scrolling auto play/pause, this is what I did.

JS video.jsx

const videoRef = useRef();
const onScreen = useOnScreen(videoRef);
useEffect(() => {
if (onScreen) {
videoRef.current.currentTime = 0;
videoRef.current.play()
} else {
videoRef.current.currentTime = 0;
videoRef.current.pause()
}
}, [onScreen]);
💡
useOnScreen is a hook that is using an observer in order to detect if the element is in the viewport of user, you can see more about it here.

CSS style.scss

.video-player {
top: 50px;
z-index: -1;
left: 0;
width: 100vw;
max-height:100vh;
overflow: hidden;
height: auto;
.full-width-video {
width: 100%;
height: auto;
}
}

For those of you reading this post after the website was changed here is a gif of it.

A visual depiction of what is being written about
To comment please authenticate