Saturday, December 3, 2011

Preventing HTML5 autobuffer with Javascript

I was looking at creating an HTML5 video website the other day but was frustrated by the fact the browsers seem to automatically download the video when the page was opened. This seemed like a waste of bandwidth especially if you have to pay for it and your site goes viral. My solution so far was to created the following script to help prevent excess bandwidth charges.

Copy the code below into a script tag in the head of your HTML document and copy the second section into a script tag at the end of the BODY. Make sure to set the style width and height of your div tags with videobox class.

function setVideo() {
        obj = this.firstElementChild;
        //Remove the extension from the filename.
        vbase = obj.src.substr(0, obj.src.lastIndexOf('.') );
        
        var vbox=document.getElementById(this.id);
        vbox.style.visibility='visible';
        var vid = document.createElement("video");
        //Transfer the size information from the image to the video.
        vid.style.width = this.style.width;
        vid.style.height = this.style.height;
        vid.controls="controls";
        vid.autoplay="autoplay";

        //Remove the onlcick action and image.
        vbox.onclick = null;
        vbox.innerHTML='';

        var vidsource;
        //Duplicate the following 4 lines for each available video source/format.
        vidsource = document.createElement("source");
        vidsource.src=vbase+'.mp4';
        vidsource.type="video/mp4; codecs=\"avc1.42E01E, mp4a.40.2\"";
        vid.appendChild(vidsource);

        vidsource = document.createElement("source");
        vidsource.src=vbase+'.ogv';
        vidsource.type='video/ogg; codecs="theora, vorbis"';
        vid.appendChild(vidsource);

        //Add the video to the document.
        vbox.appendChild(vid);
}
function html5Videos() {
        //Find all div tags with a class name of videobox.
        var x=document.getElementsByTagName("div");
        for( i=0; i < x.length; i++ ) {
                if( x[i].className == 'videobox' ) {
                        x[i].onclick = setVideo;
                }       
        }
}



html5Videos()


This is just a rough draft that I am sharing in hopes that others will find it useful and make improvements. I've tested in on the Android 2.3 browser, iPod Touch OS 4.3.3, Google Chrome 15.0.874.121 for Linux, Firefox 3.6.24.