41
This <div> will report the percentage of the video that has loaded when we retrieve it
through JavaScript:
<div>
<video loop controls id="thevideo" width="320" height="240" preload="auto">
<source src="muirbeach.webm" type='video/webm; codecs="vp8, vorbis"' >
<source src="muirbeach.mp4" type='video/mp4; codecs="avc1.42E01E, mp4a.40.2"' >
<source src="muirbeach.ogg" type='video/ogg; codecs="theora, vorbis"'>
</video>
</div>
<div id="loadingStatus">
0%
</div>
In JavaScript, we need to create the same type of eventWindowLoaded() function that
we have created many times previously in this book. This function is called when the
HTML page has finished loading. In eventWindowLoaded(), we need to create two lis‐
teners for two more events that are dispatched from the HTMLVideoElement object:
progress
Dispatched when the video object has updated information about the loading pro‐
gress of a video. We will use this event to update the percentage text in the loading
Status <div>.
canplaythrough
Dispatched when the video has loaded enough that it can play in its entirety. This
event will let us know when to start playing the video.
Below is the code that creates the listeners for those events:
function eventWindowLoaded() {
var videoElement = document.getElementById("thevideo");
videoElement.addEventListener('progress',updateLoadingStatus,false);
videoElement.addEventListener('canplaythrough',playVideo,false);
}
The updateLoadingStatus() function is called when the progress event is dispatched
from the video element. This function calculates the percent loaded by calculating the
ratio of the already-loaded bytes (videoElement.buffered.end(0)) by the total bytes
(videoElement.duration) and then dividing that value by 100. That value is then dis‐
played by setting the innerHTML property of the loadingStatus <div>, as shown in
Figure 6-5. Remember, this is only for displaying the progress. We still need to do
something after the video has loaded.
function updateLoadingStatus() {
var loadingStatus = document.getElementById("loadingStatus");
var videoElement = document.getElementById("thevideo");
var percentLoaded = parseInt(((videoElement.buffered.end(0) /
318 | Chapter 6: Mixing HTML5 Video and Canvas