Lazy Loading Video Based on Connection Speed
A large video hero can be a neat experience when done well — but adding video capability to the homepage is just asking for somebody to go in and add a 25mb video and throw all your performance optimizations out the window.
I’ve been on a few teams who wanted to do one of those full-screen background videos on the home page. And I’m usually not too thrilled to do it because how often they turn into performance nightmares. I’m embarrassed to say, there was once a day I put a 40mb background video on a page. 😬
The last time someone asked me to do it, I got curious about how I could treat the background video as a progressive enhancement for users on connections that could handle a potentially large download. I made sure to emphasize to our team the importance of a small, compressed video file, but I also wanted some programmatic magic to happen too.
Here’s a breakdown of the solution I ended up with:
- Try loading the
<source>
with JavaScript - Listen for the
canplaythrough
event. - Use
Promise.race()
to timeout the source loading if thecanplaythrough
event doesn’t fire within 2 seconds. - Remove the
<source>
and cancel the video loading if we don’t detect thecanplaythrough
event.