Skip to main content

Using HLS.js

Quickstart

HLS.js is a lightweight JavaScript library that plays HLS streams in browsers. It’s not a full video player with UI controls — it provides the streaming capability, while you use the browser’s native video controls.

Add your HTML

Create a video element with your HLS stream URL. The key parts:

  1. The aspect ratio in the container style tells the browser what size the video should be
  2. The poster is your thumbnail and data-src is your HLS stream URL
  3. Use controls to show the browser’s native video controls
<div class="hls-player" style="width:100%; position:relative; aspect-ratio:16/9; background:#000;">
<video
poster="https://worker.hesedvid.com/v1/thumbnail/org_01KAYN8RMNAEF0N243CYJCM9HR/env_A3TTAVN02AQHJTBLP7UTQ3V56ZYLNZ4/vid_K7VDWQKBCE06N0AK1O0LWDT2FQSS9A.png?width=1920&timeStamp=30"
data-src="https://worker.hesedvid.com/v1/edge_EVNENCJS37003VO58NNFZQTMWG7S66YA9TUY78/master.m3u8"
controls
playsinline
style="position:absolute; inset:0; width:100%; height:100%;"
></video>
</div>

Add your JavaScript

HLS.js handles the streaming, but some browsers (Safari, iOS) support HLS natively. The code below checks for native support first.

import Hls from 'hls.js';
document.querySelectorAll('.hls-player video[data-src]').forEach((video: HTMLVideoElement) => {
const src = video.dataset.src;
if (!src) return;
// Safari and iOS support HLS natively
if (video.canPlayType('application/vnd.apple.mpegurl')) {
video.src = src;
return;
}
// For other browsers, use HLS.js
if (Hls.isSupported()) {
const hls = new Hls({
// Buffer settings for smooth playback
maxBufferLength: 15,
maxMaxBufferLength: 30,
maxBufferHole: 0.1,
});
hls.loadSource(src);
hls.attachMedia(video);
// Handle errors gracefully
hls.on(Hls.Events.ERROR, (event, data) => {
if (data.fatal) {
switch (data.type) {
case Hls.ErrorTypes.NETWORK_ERROR:
console.error('Network error, attempting recovery...');
hls.startLoad();
break;
case Hls.ErrorTypes.MEDIA_ERROR:
console.error('Media error, attempting recovery...');
hls.recoverMediaError();
break;
default:
console.error('Fatal error');
hls.destroy();
break;
}
}
});
}
});

Demo Video

Here’s what HLS.js looks like with native browser controls:


When to Use HLS.js

HLS.js is best when you want:

  • Minimal bundle size — HLS.js is much smaller than full-featured players
  • Full control — You provide your own UI or use native browser controls
  • Framework flexibility — Easy to wrap in React, Vue, or any framework

If you need a richer UI with quality selectors, custom controls, or ad integration, consider Shaka Player or Video.js instead.

Ads

HLS.js is a streaming library, not a full video player. It does not have built-in ad support. If you need client-side ad insertion (CSAI), use a player with IMA SDK integration like Shaka Player or Video.js.