Preload HTML5 Video
» » » Preload HTML5 Video

Preload HTML5 Video

I recently had the experience of trying to preload HTML5 video for a site I develop.  It wasn’t as easy as I assumed it would be.  Before I get too in-depth, I must add a disclaimer that I have NOT cross-browser tested this solution; however, the testing I have done has been positive so far.

What is an HTML5 video tag?

The HTML5 video tag allows a developer to embed video in their web page that can support multiple formats, media queries and subtitles.  Most modern browsers request partial content from the web-server to give the impression of a streamed video; the Javascript events that are triggered enable easy interaction between the video and the DOM; and videos can also be embedded in a canvas element to enable filtering and/or animation.

A sample tag could be:

In this tag we provide 5 different video formats for the HTML5 video tag, and if they all fail we provide a Flash object (which should only be used for non-HTML5 browsers).  The above code will produce the following:

Preloading with a jQuery AJAX request

When preloading media, it’s quite common to use a jQuery AJAX request.  Something as simple as the following will preload an array of URLs.

In this example I’ve preloaded all the videos that may be displayed through the video tag I used above.  My initial problem with this method is that I have just downloaded 5 videos when only one is needed.

Preloading videos with a jQuery AJAX request

My next challenge was to limit the preloading to only the video I would use.  To do this I modified the above code to the following.

The above code will quite effectively preload the first video that the current browser is able to play.  Unfortunately, the HTML5 video tag in Chrome (and possibly other browsers) won’t use this preloaded video.  I think this is due to the video element utilising different headers when requesting the video so that only partial content is retrieved.

A solution that works

After realising my previous attempts wouldn’t work, I spent quite a bit of time researching and testing to find a solution that seems to work.  My final solution is tied in very tightly to the design of the site I was working on, but this cut-down version (it doesn’t queue preloads, nor have some other functionality I required) should work for most people.  This solutions has one pre-requisite additional to jQuery and that is jQuery AJAX Native.