Background
I have been working a lot with HTML5 <video> and delivery from Amazon S3 / CloudFront. This has been very pleasant until I recently discovered that, if you dynamically add a <video> / <source> with JavaScript would cause the movie to finish downloading even if you remove the DOM element again or even changing the “src” attribute on the object. It wont cancel/abort the download!
Reasons for adding the object dynamically was that I wanted to have control of the want the movie would start loading and the source URL would vary depending on the client connection. Also the movie is 100MB+ so I would very much like to avoid multiple downloading of the file at the same time.
Example
Appending a video element to a DOM object with id #video-container using with jQuery.
By doing this this we add an video element in the div and start playing the movie when we get the event “canPlayThrough”.
<div id="video-container"></div>
function playMovie() {
$("#video-container").append('
<video id="game-video" preload src="movie.mp4" type="video/mp4"></video>
');
// addEventListener, play when loaded //
$("#game-video").get(0).addEventListener('canplaythrough',function(a) {
a.play();
}
if(action == "restart") {
// remove the content of the video-container dom //
$("#video-container").html('');
$("#game-video").attr('src' : '');
playMovie();
}
Result
The above code would NOT cause Google Chrome to abort the downloading of the movie, in fact if we call the playMovie() multiple times the file will actually start downloading multiple times. This gets even worse if the client has a slow connection.
Solution
So how do we solve this? Instead of adding the video/src element dynamically we make sure that a video element in the html document is already created, but with empty properties. This would cause the Google Chrome to abort the download if we change the src property.
<div id="video-container"> <video id="game-video" preload src="" type="video/mp4"></video> </div>
function playMovie() {
// setting src of the video
$("#game-video").attr('src' : 'movie.mp4');
// addEventListener, play when loaded //
$("#game-video").get(0).addEventListener('canplaythrough',function(a) {
a.play();
}
if(action == "restart") {
// reset the src of the video dom //
$("#game-video").attr('src' : '');
playMovie();
}
Thats it! Hopefully this can help you out.