Media Element Text Tracks, Resource Loading, and Playback Events
How the HTML track element and media loading APIs work: subtitles, WebVTT, readyState, events, and Cloudflare Stream parity with the video element.
This page summarises the WHATWG HTML living standard for <video> and <audio>: external timed text via the track element, how a media resource is chosen and loaded, and which events fire during playback. Cloudflare Stream documents the same standard properties and events on its embedded player, plus a few stream- prefixed ad events.
track element: subtitles, captions, and WebVTT files
Section titled “track element: subtitles, captions, and WebVTT files”The track element lets authors attach explicit external timed text tracks to a media element. It does not render anything by itself; the browser exposes tracks through textTracks and the track UI.
The track element allows authors to specify explicit external timed text tracks for media elements. It does not represent anything on its own.
— WHATWG, HTML — Media elements (multipage)
Place it as a child of <video> or <audio>, before any flow content. Required attributes for a typical subtitle file: kind, src (URL to the track file), and for kind="subtitles" you must also set srclang (BCP 47). Use label for the name shown in the track menu, and default to prefer that track when the user has no stronger preference.
kind values: subtitles vs captions vs descriptions
Section titled “kind values: subtitles vs captions vs descriptions”The kind attribute selects what the track is for. Choosing the wrong kind breaks accessibility expectations and, for WebVTT, which cue format is allowed.
Keyword (kind) |
Purpose (plain terms) |
|---|---|
subtitles |
Dialogue transcription or translation when audio is heard but not understood; overlaid on video. Default if kind is omitted. |
captions |
Dialogue plus sound effects and relevant audio cues when sound may be missing or unclear; for hard-of-hearing users. |
descriptions |
Text descriptions of the visual track, for synthesis when video is not usable (e.g. blind users). |
chapters |
Chapter metadata for scripts; not shown in the default UI. |
metadata |
Timed data for scripts (scores, annotations); not shown as subtitles. |
Subtitles — Transcription or translation of the dialogue, suitable for when the sound is available but not understood (e.g. because the user does not understand the language of the media resource’s audio track). Overlaid on the video.
— WHATWG, HTML — Media elements (multipage)
If src points to WebVTT and kind is not chapters or metadata, the file must use caption or subtitle cue text per the WebVTT rules referenced from HTML.
Limits on default tracks and duplicate labels
Section titled “Limits on default tracks and duplicate labels”Authors can declare multiple tracks, but HTML constrains defaults and uniqueness:
- At most one
defaulttrack per media element forsubtitlesorcaptions(combined rule: one default among those kinds). - At most one
defaultfordescriptions, and one forchapters. - No limit on multiple
defaultmetadata tracks (unusual in practice). - You cannot have two sibling
trackelements with the samekind, same language (srclangmissing or equivalent), and samelabel(both missing or identical).
The lang attribute on a track describes the language of the label text, not the subtitle language; subtitle language comes from srclang.
Example from the specification:
<video src="brave.webm"> <track kind=subtitles src=brave.en.vtt srclang=en label="English"> <track kind=captions src=brave.en.hoh.vtt srclang=en label="English for the Hard of Hearing"> <track kind=subtitles src=brave.fr.vtt srclang=fr lang=fr label="Français"></video>track.readyState on the element
Section titled “track.readyState on the element”Each track element exposes readyState on its IDL interface: NONE (0), LOADING (1), LOADED (2), ERROR (3). Use this (and error / load events on the element) when debugging failed VTT URLs or CORS.
In-band vs out-of-band text tracks
Section titled “In-band vs out-of-band text tracks”Out-of-band tracks come from child track elements. When the element is created, the browser associates a TextTrack that starts in mode disabled and readiness not loaded, then runs the track processing model when the track should be shown or hidden and fetches src using the parent media element’s crossorigin setting.
In-band tracks are extracted from the media file itself (container-specific rules). The user agent exposes them as media-resource-specific text tracks, sets readiness to loaded, and may auto-enable forced subtitles per format rules. Details vary by container; see sourcing in-band text tracks in the multipage spec.
When a track is added or removed, addtrack / removetrack fire on the media element’s textTracks TextTrackList.
Automatic track selection
Section titled “Automatic track selection”When tracks are added, the user agent may run automatic text track selection once per element (unless blocked by the parser): honor user preferences (language, captions), else enable the first candidate with default whose mode is still disabled. For chapters / metadata with default, modes may be set to hidden rather than showing.
Media resource URL: src, source, and srcObject priority
Section titled “Media resource URL: src, source, and srcObject priority”Three ways exist to point a media element at data. Priority is fixed:
srcObject(IDL) —MediaStream,MediaSource, orBlobsrccontent attribute- One or more
<source>children
There are three ways to specify a media resource: the srcObject IDL attribute, the src content attribute, and source elements. The IDL attribute takes priority, followed by the content attribute, followed by the elements.
— WHATWG, HTML for Web Developers — Media
currentSrc returns the URL of the selected resource, or "" if there is none. Setting or changing src triggers the media element load algorithm; removing src does not, even if <source> elements remain. If itemprop is on the media element, src must also be present.
The crossorigin attribute is a CORS settings attribute; it affects fetches for the media and for track resources (see below).
Picking a format with canPlayType and source type
Section titled “Picking a format with canPlayType and source type”canPlayType(type) returns "", "maybe", or "probably". MIME types may include a codecs parameter; they describe what might play, not bitrates. On <source>, the type attribute helps the user agent skip formats it cannot render.
MEDIA_ERR_SRC_NOT_SUPPORTED (code 4) means the chosen resource was not suitable; see error codes in the developer edition.
preload, load(), networkState, and readyState
Section titled “preload, load(), networkState, and readyState”preload hints
Section titled “preload hints”preload is a hint: auto (author allows aggressive fetch), none (minimize traffic), or metadata (dimensions, duration, tracks, maybe a few frames). Missing/invalid defaults are implementation-defined; metadata is suggested as a compromise. autoplay can effectively override preload because playback requires buffering. Authors may switch from none to auto after the user starts one video among many.
media.load() resets the element and starts resource selection from scratch.
networkState: is the browser fetching?
Section titled “networkState: is the browser fetching?”| Value | Meaning |
|---|---|
NETWORK_EMPTY (0) |
Not initialised; attributes at initial values. |
NETWORK_IDLE (1) |
Resource selected; not actively using the network. |
NETWORK_LOADING (2) |
Actively downloading. |
NETWORK_NO_SOURCE (3) |
Selection running but no usable resource yet. |
loadstart and progress typically correlate with NETWORK_LOADING; suspend with NETWORK_IDLE.
readyState: can the current frame play?
Section titled “readyState: can the current frame play?”| Value | Meaning (short) |
|---|---|
HAVE_NOTHING (0) |
No data for current position. |
HAVE_METADATA (1) |
Duration (and video dimensions) known; not enough media at current time. |
HAVE_CURRENT_DATA (2) |
Current position renderable; may not advance without stalling. |
HAVE_FUTURE_DATA (3) |
Can advance slightly; text tracks ready. |
HAVE_ENOUGH_DATA (4) |
Enough buffered to play through at current rate (estimate). |
States can jump discontinuously (e.g. straight to HAVE_ENOUGH_DATA). loadedmetadata fires when duration/dimensions are known and text tracks are ready; canplay / canplaythrough align with HAVE_FUTURE_DATA and HAVE_ENOUGH_DATA respectively in the events summary.
buffered, seekable, and played return TimeRanges: ordered, non-overlapping ranges on the media timeline; start/end are inclusive.
Playback control: play(), pause, currentTime, and errors
Section titled “Playback control: play(), pause, currentTime, and errors”Common IDL properties mirror what embed APIs document: paused, ended, currentTime, duration (NaN if unknown, Infinity for unbounded streams), playbackRate, volume, muted, loop, and controls (request native UI when you are not building your own).
play() sets paused to false and begins playback if needed; pause() sets paused to true. fastSeek(time) trades precision for speed compared to assigning currentTime.
media.error is null or a MediaError with code 1–4 (MEDIA_ERR_ABORTED, NETWORK, DECODE, SRC_NOT_SUPPORTED). On failure, listen for error on the media element or on individual source / track elements.
Media events: what to listen for during load and play
Section titled “Media events: what to listen for during load and play”HTML defines a large event set on the media element. Group them by task:
Loading: loadstart, progress, suspend, abort, error, emptied, stalled, loadedmetadata, loadeddata.
Playback readiness: canplay, canplaythrough, playing, waiting.
User-visible playback: play, pause, ended, ratechange, volumechange, timeupdate.
Seeking: seeking, seeked.
Video-only: resize when videoWidth / videoHeight change.
Track lists: change, addtrack, removetrack on audioTracks, videoTracks, and textTracks.
Text and cues: cuechange on TextTrack and track elements when active cues change; enter / exit on cues. Prefer cuechange over timeupdate for metadata overlays (lower latency, less wasted work).
Per-track element: load when a track file parsed successfully; error when fetch or format fails.
The developer-oriented events summary lists preconditions (for example, waiting when readyState is low and the current time is outside buffered).
Cloudflare Stream player: standard plus stream- events
Section titled “Cloudflare Stream player: standard plus stream- events”Cloudflare documents the same surface for its player: properties such as autoplay, controls, currentTime, duration, muted, preload, and volume are described in the Player API (uploading) and Player API (viewing) pages.
We support most of the standardized media element events ↗︎.
— Cloudflare, Using the Stream Player API
Non-standard ad lifecycle events use the stream- prefix: stream-adstart, stream-adend, and stream-adtimeout when an ad-url attribute is present. Treat everything else as standard HTMLMediaElement behaviour.
metadata text tracks: timed data and cuechange
Section titled “metadata text tracks: timed data and cuechange”Non-normative guidance in HTML encourages duration-spanning cues for state like live scores: each cue should cover the interval where a value is true, not a zero-length pulse at each change. Short cues make seeking hard because scripts must scan the full cue list to avoid missing updates.
When using cues in this manner, authors are encouraged to use the cuechange event to update the current annotations. (In particular, using the timeupdate event would be less appropriate…)
— WHATWG, HTML — Media elements (multipage)
See the robotics score overlay example in best practices for metadata text tracks in the developer edition.
crossorigin and subtitle privacy
Section titled “crossorigin and subtitle privacy”Cross-origin embedding exposes duration, size, and timing even without CORS; that is considered broadly similar to img. Subtitle and metadata text are more sensitive; they are only exposed to embedding scripts when the video resource uses CORS (authors enable this with crossorigin).
However, significantly more sensitive information could be obtained if the user agent further exposes metadata within the content, such as subtitles. That information is therefore only exposed if the video resource uses CORS.
— WHATWG, HTML — Media elements (multipage)
Track fetches use a potential-CORS request with initiator type "track" and the parent’s crossorigin state. Failed fetch or unsupported format sets the text track to failed to load and fires error on the track element.
Multiple embedded audio and video tracks
Section titled “Multiple embedded audio and video tracks”Some files contain several audio or video tracks (commentary, angles, dubs). Scripts use audioTracks and videoTracks. Declaratively, a URL fragment may select tracks when the MIME type supports media fragments, e.g. myvideo#track=Alternative for a track labeled Alternative in a supporting format.
Common mistakes
Section titled “Common mistakes”- Using
captionsandsubtitlesinterchangeably; accessibility and WebVTT cue rules differ. - Omitting
srclangonkind="subtitles"(invalid per HTML). - Two
defaultsubtitle/caption tracks on one video. - Expecting JavaScript to read cross-origin VTT without CORS on the media (and track) fetch.
- Listening only to
timeupdatefor metadata overlays instead ofcuechange. - Setting
srcon many videos withpreload="auto"on a gallery page; switch tonone/metadatauntil the user plays one. - Ignoring
trackerrorandreadyState === ERRORwhen subtitles silently fail.
How to check this on your site
Section titled “How to check this on your site”- Open the page with your
<video>in a browser, enable subtitles from the native controls, and confirm the expectedlabel/ language entries match yourtrackelements (see track element). - In developer tools, select the
tracknode and checkreadyStateisLOADED(2); on failure, inspect theerrorevent and network tab for the.vttrequest and CORS headers aligned withcrossoriginon the video (out-of-band processing model). - Log
networkState,readyState, and listen forloadedmetadata,canplay, anderroron the media element while reloading; compare with the tables in HTML for Web Developers — Media. - If you use Cloudflare Stream, verify the same events in your integration against Using the Stream Player API (including
stream-ad*only whenad-urlis set). - You can check automatically in Answerwell (our tool): https://answerwell.org/workspace
Report an error or ask a question
Section titled “Report an error or ask a question”If something on this page is wrong or unclear, email yimasynthetic@gmail.com with the page URL and the exact sentence you are questioning so it can be corrected.