Created
September 5, 2012 23:57
-
-
Save chrisallick/3648116 to your computer and use it in GitHub Desktop.
Force preload of video in HTML5
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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++; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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. Sovideo.currentTime++
should really bevideo.currentTime = video.buffered.end(0)
or maybevideo.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/993683So better code might look like this (again, untested):