Improving video load performance (JS)

Video elements are used constantly around the web to allow videos, stored in your s3, or any other alternative, to be streamed to your website. While we are not YouTube and don’t want to create many small chunks for the video to allow faster time to play, we need to find a solution for our a more generic use case.

<video>
  <source src="[https://link](https://link)"> </source>
</video

This is the simple way to add a video to our website, basic html. In this case, once the url for the video is set in our source tag, the video will start to load, While this does work, the user gets a pretty slow behaviour, they already see the video element, the user has to wait the longest amount of time in order to watch the video.

So what can we do to improve this? Use native JS (Yes, native)

So lets go step by step:

  1. createElement(‘video’) will create an html element of type video (has all its attributes
  2. createElement(‘source’) will create a source element.
  3. Append the source to the video (for reference see the html snippet above).
  4. Set video preload strategy as ‘auto’ (it will start building the video buffer as soon as it gets a url.
  5. Set the video url. the video will start fetching the url it due to the preload strategy (even before being append to our HTML.
  6. Append video to HTML(or any other element for that matter) to make video player visible on screen.

— — — — —

So why does this work ?

Appending to the DOM is an “Expensive” event, it takes time. time we can take advantage of in-order to create a feeling of “perceived performance”. We want to show our uses 2 things

  1. Our website loads as fast as possible
  2. Once something is visible its usable.

Loading video will usually be the first thing on the page, and our users already kind of know this. But having an un-actionable interfaces is one of the worst experiences a user can have. So we Delay the time the video is set in the our DOM but at least when its there, its ready to go (or at worst case, in less time).

Youtube is a video platform, it will do all in their power in order to make the load time as quick as possible, in most websites this is not the case. So we can do the best we can to improve our websites with the tools we already have.

This has been tested in production on a pretty large scale platform and works faster (sadly I can’t publish numbers)