HTML and CSS Reference
In-Depth Information
<div>
<video loop controls id="thevideo" width="320" height="240" preload="auto">
<source src="muirbeach.mp4" type='video/mp4; codecs="avc1.42E01E, mp4a.40.2"' >
<source src="muirbeach.webm"type='video/webm; codecs="vp8, vorbis"' >
<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 topic. 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
loadingStatus <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 dividing that value by 100. That value is then displayed
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 once
the video has loaded.
At the time of this writing, Firefox did not support the
videobuffered
property, but this was planned for Firefox version 4.0.