Sub topic 4
Offering several formats with source
This chapter assumes you can write basic HTML, know that src points an element at a file, and know the difference between a container and a codec. No JavaScript is needed except in the last example.
Why one file is not enough
No single format plays everywhere. A src attribute names exactly one file. If the browser cannot decode it, playback fails. The source element lets you list several files and have the browser choose one.
The source element
Put source elements inside video or audio and leave out the src attribute on the parent. Each source is a void element with src and type.
<video controls width="640">
<source src="clip.webm" type="video/webm">
<source src="clip.mp4" type="video/mp4">
<p>Your browser cannot play this video. <a href="clip.mp4">Download it instead</a>.</p>
</video>The browser reads the sources from top to bottom and uses the first one it believes it can play. List your preferred format first, usually the smaller one.
The type attribute
The type attribute holds a MIME type, which is a label such as video/mp4. With it, the browser can skip a format it cannot play without downloading anything. Without it, the browser may have to fetch the file to find out.
You can add a codecs parameter for more precision:
<source src="clip.webm" type='video/webm; codecs="vp9, opus"'>Because the value contains double quotes, wrap the attribute in single quotes.
Common errors
- Putting
srcon the parent and usingsourcechildren. The parent'ssrcwins, and thesourceelements are ignored. - A wrong
type. If the label saysvideo/mp4but the file is WebM, the browser may reject it or fail while loading. - Expecting a fallback after a broken file. The browser chooses by
typeonly. If a file matches but returns a 404, it does not move to the next source. It fires anerrorevent on thatsourceelement. - Listing a heavy format first. The browser picks the first playable match, even if a later one is smaller.
Seeing which source was chosen
The currentSrc property reports the file in use.
const video = document.querySelector('video');
video.addEventListener('loadedmetadata', () => {
console.log('Playing:', video.currentSrc);
});Exercise
A page has <video src="a.mp4"> with two <source> children inside it. Which file does the browser use, and why?
Show answer
It uses a.mp4. When the parent has a src attribute, the browser ignores the source children. Remove the parent's src so the source list is used.