Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Force preload of video in HTML5
function addSourceToVideo(element, src, type) {
var source = document.createElement('source');
source.src = src;
source.type = type;
element.appendChild(source);
}
var video;
var index = 0;
$(document).ready(function(){
video = document.getElementsByTagName('video')[0];
addSourceToVideo( video, "http://video-js.zencoder.com/oceans-clip.ogv", "video/ogv");
addSourceToVideo( video, "http://video-js.zencoder.com/oceans-clip.mp4", "video/mp4");
video.addEventListener("progress", progressHandler,false);
bindKeys();
});
progressHandler = function(e) {
if( video.duration ) {
var percent = (video.buffered.end(0)/video.duration) * 100;
console.log( percent );
if( percent >= 100 ) {
console.log("loaded!");
}
video.currentTime++;
}
}
@toddpi314

This comment has been minimized.

Copy link

commented Jan 13, 2015

I'll just leave this here: http://stackoverflow.com/a/26986581/1195652

@kirtan-shah

This comment has been minimized.

Copy link

commented Aug 5, 2015

what does bindKeys() do?

@jlubeck

This comment has been minimized.

Copy link

commented Oct 19, 2015

Not working on Firefox. It just hangs in some random percentage. Any idea what might be wrong?

@WillXing

This comment has been minimized.

Copy link

commented Jan 11, 2016

Not working with my iOS device and safari too..

@josephrocca

This comment has been minimized.

Copy link

commented Jun 19, 2017

I haven't tested this, but my guess as to why it isn't working is this: the progress event fires up to 3 times per second, but more than 1 second may have downloaded per progress event. So video.currentTime++ should really be video.currentTime = video.buffered.end(0) or maybe video.currentTime = video.buffered.end(0) - 0.01 since we probably don't want to seek right to the edge just in case it triggers a fresh stream. Have a look at this SO answer for more details: https://stackoverflow.com/a/5182578/993683

So better code might look like this (again, untested):

let video = document.createElement('video');
video.src = 'video.mp4';
video.autoPlay = true;
video.onprogress = () => this.currentTime = this.buffered.end(0) - 0.01;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.