Lazy Loading Video Based on Connection Speed

Ben Robertson
DailyJS
Published in
6 min readFeb 8, 2019

--

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.

Lazy pandas love lazy loading. (Photo by Elena Loshina)

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:

  1. Try loading the <source> with JavaScript
  2. Listen for the canplaythrough event.
  3. Use Promise.race() to timeout the source loading if the canplaythrough event doesn’t fire within 2 seconds.
  4. Remove the <source> and cancel the video loading if we don’t detect the canplaythrough event.

--

--

Ben Robertson
DailyJS

I write about front end web development, accessibility, and remote work. ✍️ Writing at: https://ben.robertson.is. 🛠 Working on: https://colorbliss.com