CGJU
CGJU
July 5, 2026 · 3 min read

What is HLS.js

HLS.js is an open-source JavaScript library that implements an HLS (HTTP Live Streaming) client, capable of playing HLS streaming media in browsers that support MSE (Media Source Extensions). Developed and maintained by Dailymotion, it is currently one of the most popular web-based HLS playback solutions.

Unlike Safari browsers that natively support HLS, browsers like Chrome, Firefox, and Edge do not natively support the HLS format and require JavaScript libraries like HLS.js to implement playback functionality.

Core Features of HLS.js

  • Adaptive bitrate playback: Automatically switches video streams of different qualities based on network bandwidth
  • VOD and live streaming support: Supports both video on demand and live streaming media
  • AES-128 encryption support: Can play HLS content encrypted with AES-128
  • Subtitle support: Supports WebVTT and CEA-608/708 subtitle formats
  • Multi-language audio tracks: Supports switching between audio tracks of different languages
  • Error tolerance mechanism: Automatically retries and resumes playback during network fluctuations

HLS.js Working Principles

The working principles of HLS.js can be divided into the following core steps:

1. Loading and Parsing M3U8 Playlists

HLS.js first fetches the M3U8 playlist file via HTTP request, then parses its content, including:

  • Master Playlist: Contains multiple sub-playlists of different bitrates
  • Media Playlist: Contains specific TS segment addresses and durations
  • Encryption information: If content is encrypted, parses the encryption method and key address

2. Segment Loading and Buffer Management

After parsing the playlist, HLS.js downloads TS segments sequentially according to playback order and appends the data to the SourceBuffer of MediaSource. At the same time, it maintains a buffer queue to ensure playback continuity.

3. Adaptive Bitrate Switching

HLS.js monitors network bandwidth and buffer status in real-time, automatically switching to an appropriate bitrate video stream based on a preset algorithm to ensure a balance between playback smoothness and quality.

Getting Started: Basic Code Examples

Below is the simplest example of using HLS.js, requiring only a few lines of code to play HLS video streams in a web page.

Importing HLS.js

You can import HLS.js directly via CDN, which is the simplest way:

<script src="https://cdn.jsdelivr.net/npm/hls.js@latest"></script>

HTML Structure

Add a video element to the page:

<video id="video" controls playsinline></video>

JavaScript Initialization

Use the following code to initialize HLS.js and load the video:

const video = document.getElementById('video');
const videoUrl = 'https://example.com/stream.m3u8';

if (Hls.isSupported()) {
    const hls = new Hls();
    hls.loadSource(videoUrl);
    hls.attachMedia(video);
    hls.on(Hls.Events.MANIFEST_PARSED, function() {
        video.play();
    });
} else if (video.canPlayType('application/vnd.apple.mpegurl')) {
    video.src = videoUrl;
    video.addEventListener('loadedmetadata', function() {
        video.play();
    });
}

Common Configuration Options

HLS.js provides a wealth of configuration options that can be adjusted according to actual needs:

1. Enable Low Latency Mode

Suitable for live streaming scenarios, can effectively reduce playback latency:

const hls = new Hls({
    lowLatencyMode: true,
    liveSyncDurationCount: 3
});

2. Set Initial Quality

Specify the default quality level for playback:

const hls = new Hls({
    startLevel: 2, // Start from the 3rd quality level
    autoStartLoad: true
});

3. Configure Maximum Buffer Length

Adjust buffer size to balance memory usage and playback stability:

const hls = new Hls({
    maxBufferLength: 30, // Maximum buffer of 30 seconds
    maxMaxBufferLength: 60 // Maximum maximum buffer of 60 seconds
});

Event Listening and Error Handling

HLS.js provides a comprehensive event system that can listen to various state changes and errors:

Common Events

  • MANIFEST_PARSED: M3U8 playlist parsing completed
  • LEVEL_SWITCHED: Quality level switched
  • BUFFER_APPENDED: Data has been appended to the buffer
  • ERROR: An error occurred
  • FRAG_LOADED: Segment loading completed

Error Handling Example

hls.on(Hls.Events.ERROR, function(event, data) {
    if (data.fatal) {
        switch (data.type) {
            case Hls.ErrorTypes.NETWORK_ERROR:
                console.log('Network error, attempting to recover...');
                hls.startLoad();
                break;
            case Hls.ErrorTypes.MEDIA_ERROR:
                console.log('Media error, attempting to recover...');
                hls.recoverMediaError();
                break;
            default:
                console.log('Unrecoverable error');
                hls.destroy();
                break;
        }
    }
});

Advantages and Disadvantages of HLS.js

Advantages

  • Open source and free: Open-sourced under the Apache-2.0 license, can be used commercially for free
  • Active community: Maintained by Dailymotion, with numerous contributors on GitHub
  • Complete functionality: Supports most features of HLS, including adaptive bitrate, encryption, subtitles, etc.
  • Excellent performance: Uses Web Worker for data parsing, does not block the main thread
  • Good compatibility: Supports all modern browsers with MSE support

Disadvantages

  • Not for native HLS browsers: Browsers like Safari that natively support HLS do not need to use HLS.js
  • Requires MSE support: Some older browsers or mobile browsers may not support MSE
  • Learning curve: Mastering all configurations and APIs requires a certain learning cost

Best Practice Recommendations

1. Proper Destruction Timing

When the page unloads or switches videos, remember to call the destroy method to release resources:

window.addEventListener('beforeunload', function() {
    if (hls) {
        hls.destroy();
    }
});

2. Handling CORS Cross-Origin Issues

Ensure the M3U8 and TS file server is configured with the correct CORS headers, otherwise HLS.js cannot load resources. The following response headers need to be allowed:

  • Access-Control-Allow-Origin
  • Access-Control-Allow-Credentials

3. Set Initial Quality Reasonably

To improve user experience, it is recommended to set a reasonable initial quality based on the user's network environment, or let users manually select.

4. Listen for Errors and Gracefully Degrade

In production environments, be sure to listen for ERROR events and perform error recovery or degradation processing when necessary, providing users with friendly prompts.

Summary

HLS.js is a powerful, actively community-supported open-source HLS playback library, and the preferred solution for implementing HLS streaming media playback in web pages. Through the introduction in this article, we believe you now have a comprehensive understanding of the basic usage of HLS.js.

If you want to quickly experience HLS playback functionality, you can directly use our M3U8 online player, which can play HLS video streams in your browser without writing any code.

Related Recommendations

More great articles and useful tools

Want to Experience HLS Playback Now?

Use our free M3U8 online player, no coding required, play HLS video streams directly in your browser

Try It Now ➡