Created
March 10, 2015 11:05
-
-
Save tluyben/6261fbe2765526b88411 to your computer and use it in GitHub Desktop.
Prefetch multiple videos for offline viewing
This file contains hidden or 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
<!doctype html> | |
<html> | |
<head> | |
<title>Prefetch video</title> | |
</head> | |
<body> | |
<h1>Prefetch video</h1> | |
<p>Prefetch a video and know exactly how much is loaded using XHR.</p> | |
<video controls style="border:1px solid grey;"></video> | |
<p>Taken from:</p> | |
<ul id="videos"> | |
</ul> | |
<script> | |
var files = ["movies/1.mp4", "movies/2.mp4"]; | |
var urls = {}; | |
var video = document.querySelector('video'); | |
var videoList = document.getElementById("videos"); | |
function play_video(file) { | |
video.src = urls[file]; | |
video.play(); | |
} | |
for(var i=0;i<files.length;i++) { | |
var file = files[i]; | |
console.log(file); | |
prefetch_file(file, | |
function(url, file) { | |
urls[file] = url; | |
var li = document.createElement("LI"); | |
var a = document.createElement("A"); | |
var label = document.createTextNode(file); | |
a.appendChild(label); | |
a.href = "javascript:play_video('"+file+"');"; | |
li.appendChild(a); | |
videoList.appendChild(li); | |
}, | |
function(pc) { | |
console.log(pc) | |
}); | |
} | |
function prefetch_file(url, fetched_callback, progress_callback) { | |
var prev_pc = 0; | |
var xhr = new XMLHttpRequest(); | |
xhr.open('GET', url, true); | |
xhr.responseType = 'blob'; | |
xhr.addEventListener('load', function(event) { | |
var status = event.target.status; | |
if (status === 200) { | |
var URL = window.URL || window.webkitURL; | |
var blob_url = URL.createObjectURL(event.target.response); | |
fetched_callback(blob_url, url); | |
} else { | |
console.error(event); | |
} | |
}, false); | |
xhr.addEventListener('progress', function(event) { | |
if (event.lengthComputable) { | |
var pc = Math.round(event.loaded / event.total * 100); | |
if (pc !== prev_pc) { | |
prev_pc = pc; | |
progress_callback(pc); | |
} | |
} | |
}, false); | |
xhr.send(); | |
} | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment