Sub topic 4
Offering several formats with source
This chapter assumes you can write basic HTML, know that <audio> and <video> accept a src attribute, and have a rough idea of what a container and a codec are. Here you will learn how the <source> element lets the browser choose among several files, how it makes that choice, and what goes wrong in practice.
Why one `src` is not enough
A single src attribute points to one file. If the browser cannot decode that file, playback fails. No browser supports every container and codec, and support changes over time. The <source> element solves this by letting you list several candidate files. The browser picks the first one it thinks it can play.
<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 <source> elements are children of the media element. They have no closing tag. The <p> is fallback content, which only browsers that do not understand <video> display. Fallback content is covered in the next chapter.
How the browser chooses a source
The browser runs a resource selection algorithm. The parts that matter in daily work are these:
- If the media element has a
srcattribute, the browser uses it and ignores any<source>children. - Otherwise it looks at each
<source>child in document order. - For each one, it skips the candidate if the
typeattribute is present and the browser knows it cannot play that type. It also skips the candidate ifmediais present and does not match (this is only meaningful in older specifications, see the callout below). - It tries to fetch the first remaining candidate. If the fetch fails or the file cannot be decoded, it moves to the next one.
- If no candidate works, the element fires an
errorevent on the last<source>and the media element'snetworkStatebecomesNETWORK_NO_SOURCE.
Two consequences follow from this algorithm.
- Order is your preference order. Put the file you most want browsers to use first.
- Only the first matching candidate is used. The browser does not combine files or pick the smallest one.
The type attribute
The type attribute holds a MIME type, optionally with a codecs parameter. Its job is to let the browser skip a file without downloading it.
<audio controls>
<source src="song.opus" type='audio/ogg; codecs="opus"'>
<source src="song.m4a" type='audio/mp4; codecs="mp4a.40.2"'>
<source src="song.mp3" type="audio/mpeg">
</audio>Note the quoting. The codecs value contains double quotes, so the attribute value uses single quotes.
Without type, the browser must fetch the start of each file and try to decode it. That costs a network request per wrong guess. With type, an unsupported candidate is skipped immediately.
Be precise about codecs. A container name alone is ambiguous, because one container can hold several codecs.
| Container | MIME type | Common codecs in it |
|---|---|---|
| MP4 | `video/mp4` | H.264 (`avc1`), H.265, AV1 with AAC audio |
| WebM | `video/webm` | VP8, VP9, AV1 with Vorbis or Opus audio |
| Ogg | `audio/ogg` | Vorbis, Opus |
| MP3 | `audio/mpeg` | MP3 |
If you write type="video/mp4" and the file holds H.265, a browser may accept the type and then fail to decode. Adding codecs makes the pre-check accurate:
<video controls width="640">
<source src="clip-av1.mp4" type='video/mp4; codecs="av01.0.05M.08, mp4a.40.2"'>
<source src="clip-h264.mp4" type='video/mp4; codecs="avc1.42E01E, mp4a.40.2"'>
</video>Here the more efficient AV1 file comes first. Browsers that cannot decode AV1 skip it without downloading, and use the H.264 file.
Choosing a format set
A practical set depends on your audience and on how much storage and encoding work you accept.
- For video, an H.264 plus AAC file in MP4 is the widest compatibility choice. Most current browsers play it.
- Adding a WebM file with VP9 or AV1 can reduce file size at the same quality, so list it first.
- For audio, MP3 and AAC in MP4 are widely supported. Opus in Ogg or WebM is efficient but has had uneven support on some Apple platforms, so keep an MP3 or AAC fallback.
Check current support tables before you commit. Support changes, and this chapter cannot list it exactly.
Errors and debugging
Error events come from source, not the media element
When a <source> fails to load, the error event fires on that <source> element. It does not bubble. Listening on the <video> element catches nothing unless you use the capture phase.
const video = document.querySelector('video');
video.addEventListener('error', (event) => {
const source = event.target;
if (source instanceof HTMLSourceElement) {
console.warn('Source failed:', source.src);
}
}, true);
video.addEventListener('loadedmetadata', () => {
console.log('Using:', video.currentSrc);
});The true argument turns on capture, so the listener sees the event while it travels down to the <source>. The currentSrc property tells you which file the browser actually chose.
Changing sources after load
Adding or editing <source> elements after the page has loaded does not restart selection. The browser has already chosen. Call load() to run the algorithm again:
const video = document.querySelector('video');
video.querySelector('source').src = 'other-clip.mp4';
video.load();Calling load() resets playback to the start. If you only have one file, it is simpler to set video.src directly.
A wrong MIME type from the server
If the server sends a file with the wrong Content-Type header, some browsers refuse to play it even when your type attribute is right. For example, an .mp4 file served as text/plain can fail. Server delivery is covered in a later chapter. When a source fails for no clear reason, check the response headers in the browser's network panel.
Mistakes seen often
- Putting
<source>inside a media element that also hassrc. The<source>elements are ignored. - Writing a
typethat does not match the file, so a playable file is skipped. - Listing the least compatible file first and wasting a request or an unsupported decode.
- Using
<source>outside<audio>,<video>, or<picture>. It does nothing there.
Checking your work
Test with a browser that lacks support for your first choice, or temporarily reorder the sources. Confirm in the network panel that unsupported candidates with a correct type are never requested. Confirm that currentSrc matches your expectation.
Exercise
A page has <video controls src="a.mp4"> with two <source> children inside it: one for b.webm and one for c.mp4. Which file does the browser load, and why? Then name one fix so that all three files are considered.
Show answer
It loads a.mp4. When the media element has a src attribute, the browser uses it and ignores <source> children. To make the browser consider the files, remove the src attribute from <video> and list all three as <source> elements, with the preferred file first.
Exercise
You added a <source> element with a type of video/mp4 for a file encoded with H.265. A browser without H.265 support downloads it, fails, and then tries the next source. What change to the type attribute lets the browser skip it without downloading? Why does error not reach a listener on the <video> element by default?
Show answer
Add the codecs parameter, for example type='video/mp4; codecs="hvc1.1.6.L93.B0"', so the browser can tell it cannot play the file before fetching. The error event fires on the <source> element and does not bubble, so a listener on <video> only sees it if registered with the capture option (true as the third argument).