Video Playback and Streaming in the Browser
|
This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production. |
Baseline date: 2026-10-07. The packaging that produces the files this page plays is in
video streaming: HLS, DASH and CMAF. On the client, adaptive
streaming needs a player that downloads manifests and segments and feeds them to the <video> element.
The video element
The attributes (poster, preload, playsinline, muted) are explained with the other native attributes in
native HTML images and lazy loading. A single MP4 with
faststart is the simplest option, see encoding. Use
adaptive streaming for anything long, or for audiences on varied connections.
How adaptive playback works
Safari, iOS and tvOS play HLS natively: set video.src to the .m3u8 URL. Other browsers cannot play HLS or DASH
natively, so a JavaScript player downloads the manifest, fetches segments with fetch, and appends them to a
SourceBuffer with the Media Source Extensions
(MSE) API. The player measures throughput and the buffer level, and chooses the next segment’s rendition, which is the
ABR (adaptive bitrate) algorithm. iPhones historically lacked MSE. Recent iOS versions provide
ManagedMediaSource, a variant of MSE in which the browser can ask the page to stop or resume buffering (to save
power), and current versions of hls.js and Shaka Player use it. Check
MDN ManagedMediaSource for the supported versions.
The segment loop
Every JavaScript player runs the same loop, and each term in the player configuration maps to one arrow of it.
The player keeps the buffer between a low and a high target (typically tens of seconds). A low buffer makes it pick a cheaper rendition quickly, and a full buffer lets it step up. This is why a fast network gives sharp video after a few segments rather than at the first frame.
Choosing a rendition
The exact algorithms differ, but they all combine a smoothed bandwidth estimate with a safety margin and with the size of the player. The estimate is an exponentially weighted moving average, often with a fast and a slow half-life, and the smaller of the two is used so that a drop is believed quickly while a rise is trusted slowly. The function below is a simplified model of that decision over the rendition ladder from the backend (see encoding):
const ladder = [
{ height: 360, bitrate: 800_000 },
{ height: 540, bitrate: 1_800_000 },
{ height: 720, bitrate: 3_000_000 },
{ height: 1080, bitrate: 6_000_000 },
];
export function chooseLevel({ levels, bandwidth, playerHeight, dpr = 1, safety = 0.8 }) {
const budget = bandwidth * safety; // never plan to use the whole estimated throughput
const maxHeight = playerHeight * dpr; // pixels the player can actually show
let best = 0;
levels.forEach((level, index) => {
if (level.bitrate <= budget && (level.height <= maxHeight || index === 0)) best = index;
});
return best;
}
console.log(ladder[chooseLevel({ levels: ladder, bandwidth: 5_000_000, playerHeight: 720 })]); // 720p, 3 Mbit/s
console.log(ladder[chooseLevel({ levels: ladder, bandwidth: 10_000_000, playerHeight: 360 })]); // 360p, capped by the player
console.log(ladder[chooseLevel({ levels: ladder, bandwidth: 600_000, playerHeight: 720 })]); // 360p, the floor
At 5 Mbit/s the budget is 4 Mbit/s, so 720p (3 Mbit/s) is chosen even though 1080p is a bigger rendition. A 360-pixel
player on a 10 Mbit/s link still gets 360p because anything larger would waste bandwidth, and that second rule is what
hls.js capLevelToPlayerSize implements. Both rules together are the reason a ladder with too few rungs wastes either
quality or bandwidth: with no rung between 3 and 6 Mbit/s, a 5 Mbit/s viewer is stuck at 720p.
hls.js
hls.js plays HLS in browsers that support MSE, and is the usual choice when you only need HLS.
npm install hls.js
import Hls from 'hls.js';
export function attachHls(video, url) {
if (video.canPlayType('application/vnd.apple.mpegurl')) {
video.src = url; // native HLS: Safari, iOS
return () => {};
}
if (Hls.isSupported()) {
const hls = new Hls({ capLevelToPlayerSize: true }); // do not pick a rendition larger than the player
hls.loadSource(url);
hls.attachMedia(video);
hls.on(Hls.Events.ERROR, (_event, data) => {
if (data.fatal && data.type === Hls.ErrorTypes.NETWORK_ERROR) hls.startLoad();
else if (data.fatal && data.type === Hls.ErrorTypes.MEDIA_ERROR) hls.recoverMediaError();
else if (data.fatal) hls.destroy();
});
return () => hls.destroy(); // call on unmount
}
return () => {};
}
Order matters. Prefer native HLS where it exists, since it uses hardware decoding and the platform’s own ABR. Reference: hls.js API documentation.
dash.js
dash.js is the reference DASH player of the DASH Industry Forum.
import * as dashjs from 'dashjs';
const player = dashjs.MediaPlayer().create();
player.initialize(document.querySelector('video'), 'https://cdn.example.com/videos/42/manifest.mpd', false);
player.updateSettings({ streaming: { abr: { autoSwitchBitrate: { video: true } } } });
It needs MSE, so it does not play on browsers without it. Use it when you must serve DASH, for example with a DASH-only DRM setup. Reference: dash.js documentation.
Shaka Player
Shaka Player plays both HLS and DASH, with DRM (Widevine, PlayReady, FairPlay), offline storage and a UI library. It is the right choice when you want one player for both manifest types.
import shaka from 'shaka-player';
shaka.polyfill.installAll();
if (shaka.Player.isBrowserSupported()) {
const video = document.querySelector('video');
const player = new shaka.Player();
await player.attach(video);
player.configure({ abr: { enabled: true } });
await player.load('https://cdn.example.com/videos/42/master.m3u8'); // or a .mpd URL
}
The import path and the attach call differ between major versions, so follow the
basic usage tutorial for the version you install.
Video.js
Video.js is a full player with a skin, plugins and accessibility features. It plays HLS and DASH through its bundled streaming engine (VHS) where MSE is available, and falls back to native HLS.
<video id="player" class="video-js" controls preload="none" width="1280" height="720"
poster="/videos/42/poster.jpg" data-setup="{}">
<source src="https://cdn.example.com/videos/42/master.m3u8" type="application/x-mpegURL">
</video>
Choose Video.js when you need a consistent UI across browsers and a plugin ecosystem (thumbnails on the progress bar from a sprite sheet, analytics, ads). Choose hls.js or Shaka Player with the native controls when you want the smallest page.
Start the player on demand
A player library is 100 KB or more, and a list page can hold dozens of videos. Create the player only when the video comes
near the viewport, load the library with a dynamic import(), and destroy it when the component goes away. The function
below keeps the player module out of the initial bundle and guards the race where the user navigates away while the module
is still loading:
// play-on-demand.js
export function playOnDemand(video, loadPlayer, rootMargin = '400px') {
let destroy = () => {};
let started = false;
let cancelled = false;
const observer = new IntersectionObserver(async ([entry]) => {
if (!entry.isIntersecting || started) return;
started = true;
observer.disconnect();
const { attach } = await loadPlayer();
if (cancelled) return; // unmounted while the chunk was loading
destroy = attach(video, video.dataset.src);
}, { rootMargin });
observer.observe(video);
return () => { cancelled = true; observer.disconnect(); destroy(); };
}
// usage: the second argument is a dynamic import of a module exporting attach(video, url) -> cleanup,
// for example the attachHls function above
const stop = playOnDemand(document.querySelector('video[data-src]'), () => import('./attach-hls.js'));
Combined with preload="none" and a poster, the page downloads only the poster until the video is both near the viewport
and played. Note that the player starts buffering as soon as attach runs, so for lists prefer to attach on the first
click or tap, using the same function with a click listener instead of the observer. Calling the returned function twice
is harmless, and calling it before the intersection prevents the player from ever being created.
Watching quality at run time
Every player exposes the switch events, and the media element exposes dropped frames. They are the numbers to send to analytics to see whether the ladder and the CDN work for real viewers:
import Hls from 'hls.js';
export function watchQuality(hls, video, report) {
hls.on(Hls.Events.LEVEL_SWITCHED, (_event, data) => {
const level = hls.levels[data.level];
report({ type: 'level', height: level.height, bitrate: level.bitrate });
});
hls.on(Hls.Events.FRAG_LOADED, (_event, data) => {
const stats = data.frag.stats;
const seconds = Math.max((stats.loading.end - stats.loading.first) / 1000, 0.001);
report({ type: 'throughput', bitsPerSecond: Math.round((stats.loaded * 8) / seconds) });
});
return setInterval(() => {
const quality = video.getVideoPlaybackQuality();
report({ type: 'frames', dropped: quality.droppedVideoFrames, total: quality.totalVideoFrames });
}, 10_000);
}
Clear the returned interval on unmount, next to hls.destroy(). A high share of dropped frames on a low-end device
means the rendition is too heavy to decode, which a bandwidth-based algorithm cannot see: cap the maximum height for
those devices, or add a lower-resolution, lower-profile rung.
Which player
| Player | Formats | DRM | Notes |
|---|---|---|---|
Native |
MP4, WebM, and HLS in Safari |
Platform DRM |
Smallest. No ABR outside Safari. |
hls.js |
HLS |
Basic (EME) |
The common choice for HLS only. Lightweight. |
dash.js |
DASH |
Yes |
DASH Industry Forum reference player. |
Shaka Player |
HLS and DASH |
Yes |
One player for both. Includes offline storage and a UI. |
Video.js |
HLS and DASH |
Via plugins |
Full UI and plugins. |
Delivery details
-
CORS. A JavaScript player fetches manifests and segments with
fetchor XHR, so the CDN must sendAccess-Control-Allow-Originfor your site, and allow theRangeheader if byte ranges are used. -
Private video. Authorise a whole path prefix with signed cookies or a token, not one signed URL per file, see video streaming. Cross-origin cookies need
withCredentialsin the player configuration andSameSite=None; Securecookies, so serving the video from a subdomain of your site is simpler. -
Posters and covers. Generate them as described in video covers and thumbnails, and show a BlurHash while the poster loads, see BlurHash in the browser.
-
Start-up time. Start on a low or middle rendition, keep segments short (2 to 6 seconds) and serve the first segments from the CDN edge. The first rendition chosen is set in the player (
startLevelin hls.js,abrandbandwidthestimates in Shaka Player and dash.js). -
Unload. Destroy players on unmount, otherwise SPA navigation leaks MSE buffers and keeps downloading.