A patched build of hls.js with Whole Segment Preload built in. Originally built for Tsukinatsune's own projects prefetches every HLS segment into memory so seeks are instant with no buffering delay.

mascot character
WSP-HLS

hlsv2 Documentation

hlsv2.31 is a patched build of hls.js with the WSP-HLS (Whole Segment Preload) extension built in. It adds hls.wsphls() a method that prefetches every HLS segment into memory in the background, then installs a cache-first loader so seeks are instant with no buffering spinner.

Instant Seeks
Segments cached in memory before playback reaches them seeks never trigger a network wait.
Drop-in Replace
Same API as standard hls.js. Swap the script tag, call wsphls(), done.
Encrypted Streams
IV is preserved on cache hits so AES-128 encrypted streams play back correctly.
Base: Built on hls.js. All standard hls.js APIs remain available. The WSP-HLS patch adds only three new methods to Hls.prototype and does not change any existing behaviour.

Purpose & Use Cases

WSP-HLS is designed for applications where seek latency matters and CDN egress cost is a concern. Standard hls.js buffers forward it cannot predict where a user will seek. WSP-HLS solves this by fetching the entire video into memory up front.

1
Instant random seeks
Every segment is already in memory. Scrubbing to any point plays back with zero network wait, regardless of how far ahead or behind the current position.
2
CDN cost reduction
Each segment is fetched exactly once. Rewatches, replays, and repeated seeks never generate additional CDN requests the cache is shared across all Hls instances on the same page.
3
Review & QA tools
Post-production, sports analysis, and content moderation tools require random-access playback. WSP-HLS makes HLS viable for these workflows.
4
High-seek-frequency content
Anime episodes, tutorials, and music videos attract viewers who skip intros, jump to remembered scenes, and rewind frequently. WSP-HLS absorbs all of that without repeated CDN hits.

Cost Optimization

WSP-HLS is a CDN egress cost control mechanism. Standard hls.js re-fetches a segment from your CDN every time a seek lands outside the 30-second forward buffer. WSP-HLS prefetches every segment once into memory after that, every seek is served from window.__hlsSegmentCache at zero network cost.

The key insight: each segment is fetched exactly once, regardless of how many times the user seeks to it. This means your CDN sees N segment requests total per viewer one per segment instead of N × seeks.

How wsphls() eliminates seek-driven CDN cost

Here is the full pattern. After MANIFEST_PARSED fires, call wsphls(). It prefetches every segment in the background, installs a CacheFirstLoader, and resolves the Promise when complete. All subsequent seeks hit the in-memory cache zero network requests.

javascript full wsphls() cost-saving setup
<script src="https://cdn.jsdelivr.net/gh/Tsukinatsune/CDN-Javascript-project@main/hlsv2.31.js"></script>
<script>
var video = document.getElementById('video');
var src   = 'https://example.com/stream/playlist.m3u8';

if (Hls.isSupported()) {
  var hls = new Hls();
  hls.loadSource(src);
  hls.attachMedia(video);

  hls.on(Hls.Events.MANIFEST_PARSED, function() {
    video.play();

    // wsphls() fetches every segment into window.__hlsSegmentCache.
    // Once resolved, CacheFirstLoader is installed as hls.config.fLoader.
    // Every subsequent seek is served from memory  CDN is never hit again.
    hls.wsphls({
      concurrency: 6,        // parallel fetch workers
      onProgress: function(p) {
        // p = { prefetched, total, failed }
        // Drive a progress bar: p.prefetched / p.total
        console.log(p.prefetched + '/' + p.total + ' segments cached');
      }
    }).then(function(result) {
      // result.prefetched   segments now in cache
      // result.total        total segments in level
      // result.failed       array of { url, error } for any failures
      console.log('All segments cached. Seeks are now instant.', result);

      // From this point, window.__hlsSegmentCache holds every segment.
      // Inspect: window.__hlsSegmentCache.size
      // Clear to free RAM: window.__hlsSegmentCache.clear()
    });
  });
}
</script>

Adaptive prefetch cap bandwidth cost on long content

For large or high-bitrate streams, prefetching the full video may exceed practical RAM or bandwidth limits. Use endTime to prefetch only the high-seek-risk region and let normal hls.js buffering handle the rest.

javascript size-aware wsphls() call
hls.on(Hls.Events.MANIFEST_PARSED, function() {
  video.play();

  // Estimate how large the full video is at the current level
  var level   = hls.levels[hls.currentLevel >= 0 ? hls.currentLevel : 0];
  var durS    = (level && level.details) ? level.details.totalduration : 0;
  var estMB   = level ? (level.bitrate / 8 / 1e6) * durS : 0;

  var opts = { concurrency: 6 };

  if (estMB > 800) {
    // Very large (e.g. 1080p movie)  prefetch intro skip zone only (first 5 min)
    opts.concurrency = 3;
    opts.endTime = 300;
  } else if (estMB > 300) {
    // Medium (e.g. 720p episode > 30 min)  prefetch first 20 min
    opts.concurrency = 4;
    opts.endTime = 1200;
  }
  // else: under 300 MB (short clip or low bitrate)  prefetch everything

  hls.wsphls(opts).then(function(result) {
    // CacheFirstLoader is now installed. All seeks within the prefetched
    // window are served from window.__hlsSegmentCache  no CDN requests.
    console.log(
      'Prefetch done: ' + result.prefetched + '/' + result.total +
      ' segments. Failed: ' + result.failed.length
    );
  });
});

Why it saves money

With standard hls.js, every seek outside the forward buffer fires a CDN request. With wsphls(), each segment is fetched from the CDN exactly once during prefetch. The cache is shared across all Hls instances on the page, so rewatches and quality switches also cost nothing.

Illustrative numbers 24 min episode, 720p
Segments total
~120 segments
@ 12 s each × 24 min
CDN hits with wsphls()
120 per viewer
one prefetch, then zero
Seek-driven hits saved
seeks × segment refetches
eliminated per viewer
* Actual savings depend on average seek count, segment duration, bitrate, and CDN pricing. Break-even is 1 seek per viewer beyond that every seek is pure savings.
Rule of thumb: WSP-HLS pays for itself the moment a viewer seeks more than once. One re-fetched segment costs the same as one prefetched segment so break-even is 1 seek per viewer. Every seek after that is zero CDN cost.

CDN Cost Calculator real-world model

This calculator models what actually happens at CDN level: viewers don't all seek equally, standard hls.js has a 30-second forward buffer that absorbs nearby seeks for free, and wsphls() itself generates egress during prefetch. There are real conditions where wsphls() costs more those are shown honestly.

CDN Cost Calculator
scenario:
Stream
Quality
Real measured bitrates: 360p ≈ 400 kbps · 720p ≈ 1 Mbps · 1080p ≈ 2.5 Mbps · 4K ≈ 8 Mbps (H.264). H.265/AV1 roughly half.
Video duration 24 min
Short clip (1–5 min) · Episode (20–48 min) · Movie (90–180 min)
Segment duration 6 s
Most real HLS streams use 4–6 s. Affects how many CDN requests each seek triggers and how granular wsphls() prefetch is.
CDN provider
Cloudflare Stream: $0.030/GB · no per-request fee (pricing as of 2024–2025 public rate cards; verify current rates).

Audience & Behaviour
Daily unique viewers 50 k
Avg completion rate 65%
Reality check: most viewers don't finish. Netflix internal data ~70 % for episodes, ~55 % for movies. Standard hls.js only fetches what's played wsphls() fetches everything regardless of completion.
Avg seeks per viewer 10
Typical observed ranges: linear movies 0–2 · TV episodes 3–8 · anime 5–15 · review/QA tools 20–60. Standard hls.js re-fetches a segment on every seek outside the 30 s forward buffer.
Seeks outside 30 s buffer 75%
Seeks within 30 s ahead cost nothing in either model. Only far seeks generate CDN requests in standard hls.js. For linear viewers who scrub slightly ahead this can be very low.
Mobile audience share 40%
Mobile viewers have tighter RAM limits. wsphls() on a full 4K movie can crash the tab the calculator flags this and assumes a 5-min prefetch window (endTime: 300) on mobile for large files.
Per-viewer numbers
Total segments
Full video size
Actual data played (avg completion)
Far seeks (outside 30 s buffer)

Daily CDN egress
Standard hls.js
wsphls() (full video prefetch)

Daily CDN cost
Standard hls.js
With wsphls()
Daily saving
Key factors

Real-World Scenarios

Standard HLS already handles buffering ahead of playback and reconnects after dropouts. WSP-HLS is useful in a narrower, more specific set of situations where the bottleneck is not the stream itself but the cost and latency of segment requests at unpredictable seek targets.

WSP-HLS earns its keep when seeks land far outside the standard 30–60 s forward buffer. The sections below explain how to adapt it for every situation including live streams, long content, and mobile rather than bypassing it.
Scenario A
Anime site high seek frequency on short fixed-length content

Why standard HLS is not enough here: A 24-minute episode is short enough to fully cache in reasonable time and memory (~100–200 MB at 720p). But the seek pattern is brutal users skip OPs at 1:30, jump to a remembered scene, rewind 30 seconds, skip the recap at the start. These seeks are random and hit outside the 30-second forward buffer constantly. Standard HLS re-fetches a segment on every one of these seeks.

What WSP-HLS actually fixes: After the prefetch completes (typically within the first 2–3 minutes of playback on a decent connection), every seek is served from memory. The CDN sees exactly N segment requests total one per segment regardless of how many times the user scrubs. For a site with 100k daily active viewers each seeking 5 times per episode, that is a measurable reduction in CDN egress and request count.

The math: 24 min episode × 1 Mbps (720p) = ~180 MB. At 6 concurrent fetches that takes ~30 s on a 30 Mbps connection. The episode is fully in RAM before the viewer finishes the cold open. Every seek after that costs zero CDN requests.
Scenario B
Movie platform viewer behavioural data as a prefetch signal

The real opportunity: You know things about your viewers that generic HLS players don't use. Completion rate, average seek count per session, device class, and connection speed are all signals you can act on before deciding whether to call wsphls() at all and with what options.

Signal you haveWhat it implieswsphls() decision
Viewer historically seeks 8+ times per watch Each seek is a CDN hit without caching. Heavy seeker = heavy cost without WSP-HLS. Full prefetch, high concurrency
Viewer watches linearly, rarely seeks Standard 30s forward buffer is sufficient. wsphls() just burns bandwidth early. Prefetch a short window only e.g. endTime: 300 to cover likely seeks without wasting bandwidth on content they'll play straight through
Content is a rewatch (user has seen it before) They will seek to specific remembered scenes immediately. Every seek is a cache miss without WSP-HLS. Full prefetch before play even starts
Content is > 90 min at 1080p (> 800 MB) Full prefetch is impractical on mobile and risks tab crash on low-memory devices. Prefetch first 20 min only (endTime: 1200)
javascript signal-driven prefetch
function decidePrefetch(hls, analytics) {
  var avgSeeks   = analytics.user.avgSeeksPerSession; // from your backend
  var isRewatch  = analytics.content.rewatchCount > 0;
  var durationS  = hls.levels[hls.currentLevel]?.details?.totalduration || 0;
  var bitrateKbps = hls.levels[hls.currentLevel]?.bitrate / 1000 || 0;
  var estMB      = (bitrateKbps / 8 / 1000) * durationS;

  // Linear watcher on long content  prefetch a short safety window only
  if (avgSeeks < 2 && !isRewatch && estMB > 500) opts.endTime = 300;

  var opts = { concurrency: 6 };

  // Limit to first 20 min if content is large
  if (estMB > 500) opts.endTime = 1200;

  // Rewatchers: start prefetching before play  they seek immediately
  if (isRewatch) opts.concurrency = 10;

  hls.wsphls(opts);
}
Scenario C
Review / QC tools random-access is the entire point

The problem standard HLS was never designed for: Video review tools (post-production QC, sports analysis, content moderation) don't play video they interrogate it. The user jumps to a timestamp, pauses, jumps back 2 seconds, jumps to a completely different scene, compares two moments 40 minutes apart. There is no linear playback pattern at all. The standard forward-buffer strategy is useless here every jump is a cold seek into uncached territory.

WSP-HLS is the only HLS-based solution for this: Once prefetch completes, the entire video is in memory and every seek is instantaneous. This is the use case where it goes from "nice to have" to genuinely necessary the alternative is per-seek latency that makes the tool frustrating to use.

Best fit: Clips under 20 minutes at 1080p. For longer content, split into scenes and prefetch one scene at a time, swapping the Hls instance per scene.

How to adapt for every situation

SituationHow to adapt wsphls()
Live stream Call wsphls() after the stream ends and the VOD replay becomes available at that point all segments are fixed and cacheable. During live, let standard HLS run normally.
Linear viewer who rarely seeks Prefetch a short safety window endTime: 300 (5 min). Covers the rare seek without burning bandwidth on content they will play straight through.
Content > 2 h at 1080p on mobile Prefetch in a rolling window: cache the next 20 minutes ahead of the playhead by re-calling wsphls({ startTime, endTime }) on a timer as the user advances.
Mid-video connection drop on linear playback The standard 30–60 s forward buffer already covers brief dropouts. Pair with maxRetry: 5 in wsphls() so any segment that failed during the dropout is retried silently when the connection returns.
Very low bitrate content (sub 500 kbps) Seek latency is already low, so wsphls() is optional. Still worth running with concurrency: 2 to cap the extra bandwidth the cache still eliminates duplicate fetches if the user rewinds.

Live Demo HLS Playback

Try it live: paste a .m3u8 URL or paste raw M3U8 playlist text directly. Once wsphls() completes prefetch, seeking is instant with no buffering spinner.

presets:
Loading stream…
wsphls mode:
Initialising…
Cache: 0 segments
After the prefetch bar reaches 100%, try seeking anywhere in the timeline it should be instant with no rebuffer. URL tab: paste any .m3u8 URL or pick a preset. Raw M3U8 tab: paste a full playlist directly segment URLs must be absolute. Use the wsphls mode row to test default, level: N, or allLevels before loading. Loading always fully resets the Hls instance and cache.

Installation

No build step needed. Load the script from the CDN or host it yourself.

CDN (recommended)

html
<script src="https://cdn.jsdelivr.net/gh/Tsukinatsune/CDN-Javascript-project@main/hlsv2.31.js"></script>

Self-hosted

Download hlsv2.31.js and serve it from your own origin:

html
<script src="/js/hlsv2.31.js"></script>

Module / ESM

The file ships a UMD bundle. In a module context use a dynamic import or a bundler alias:

javascript
// Bundler (webpack / vite)  alias hls.js to hlsv2.31.js in config
import Hls from 'hls.js'; // now resolves to your patched file

// Or: dynamic import after the script tag loads
const Hls = window.Hls;

Quick Start

A minimal working example stream plays normally, then all segments are prefetched in background so seeks become instant.

html
<!DOCTYPE html>
<html>
<head>
  <script src="https://cdn.jsdelivr.net/gh/Tsukinatsune/CDN-Javascript-project@main/hlsv2.31.js"></script>
</head>
<body>
  <video id="video" controls width="800"></video>

  <script>
    const video = document.getElementById('video');
    const src   = 'https://example.com/stream/playlist.m3u8';

    if (Hls.isSupported()) {
      const hls = new Hls();
      hls.loadSource(src);
      hls.attachMedia(video);

      hls.on(Hls.Events.MANIFEST_PARSED, function() {
        video.play();

        // Start background prefetch  returns a Promise
        hls.wsphls({ concurrency: 6 }).then(function(result) {
          console.log('Prefetch done:', result);
          // result = { prefetched: N, total: N, failed: [] }
        });
      });

    } else if (video.canPlayType('application/vnd.apple.mpegurl')) {
      // Safari native HLS  wsphls() not available
      video.src = src;
    }
  </script>
</body>
</html>
WSP-HLS

wsphls() Call Signatures

Three ways to call hls.wsphls() giving precise control over which quality level is prefetched. The default (no arguments) still prefetches the current level as before.

1 · Default prefetch (current level)

Call with no arguments. Prefetches whichever level hls.js is currently playing. Behavior is identical to the original API.

javascript
// Prefetch the current (ABR-selected) quality level
hls.wsphls();

2 · Prefetch a specific quality level

Pass { level: N } to lock prefetch to an exact quality index. 0 is always the lowest bitrate; higher indices correspond to higher qualities. Useful for "warm up 360p only" patterns where bandwidth is limited, or for pre-loading a known quality before the user switches.

javascript
// Force a specific quality index (0 = lowest)
hls.wsphls(); // default  uses current ABR level

// Prefetch level 2 only (e.g. 380p in your playlist)
hls.wsphls({ level: 2 });

// Prefetch 1080p (index 4, if your playlist has 5 levels)
hls.wsphls({ level: 4 });
Index is 0-based and playlist-order. Check hls.levels.length and inspect hls.levels[N].height to confirm which resolution maps to which index before hardcoding a level number.

3 · Prefetch all quality levels at once

Pass { allLevels: true } to prefetch every rendition in the master playlist simultaneously. Segment workers are shared across all levels, so the concurrency option still applies globally. This is the highest memory usage mode best for short videos or when storage is not a concern.

javascript
// Prefetch every quality level in the master playlist
hls.wsphls({ allLevels: true }).then(function(result) {
  console.log('All levels done:', result);
});

At a glance

Call Levels prefetched Memory cost When to use
hls.wsphls() Current ABR level Low Default. Good for most use cases one quality, smallest RAM footprint.
hls.wsphls({ level: N }) Exactly level N Low Pin to a known quality (e.g. warm up 360p before user requests HD).
hls.wsphls({ allLevels: true }) All levels High Short clips, review tools, or offline-capable players where all bitrates are needed.

Quality Settings

Quality level selection directly controls prefetch size and CDN egress. Inspect hls.levels before deciding which level to cache. The array is sorted lowest → highest bitrate (index 0 = lowest quality).

javascript inspect available levels
// After MANIFEST_PARSED fires, inspect what levels exist
hls.on(Hls.Events.MANIFEST_PARSED, function() {
  hls.levels.forEach(function(lvl, i) {
    console.log(i, lvl.height + 'p', Math.round(lvl.bitrate / 1000) + 'kbps');
    // → 0  360p  400kbps
    // → 1  720p  1000kbps
    // → 2  1080p 2500kbps
  });

  // Pick lowest bitrate to minimise prefetch data cost
  hls.wsphls({ level: 0 });

  // Or pick the level closest to a target resolution
  var targetHeight = 720;
  var idx = hls.levels.reduce(function(best, lvl, i) {
    return Math.abs(lvl.height - targetHeight) < Math.abs(hls.levels[best].height - targetHeight) ? i : best;
  }, 0);
  hls.wsphls({ level: idx });
});

Quality vs. memory trade-off

Higher quality means larger prefetch. The table below shows approximate in-memory size for a 24-minute episode at common quality levels. Use hls.levels[N].bitrate and your stream's duration to compute it exactly.

Quality Typical bitrate 24 min episode (est.) Prefetch recommendation
360p 400 kbps ~72 MB Always safe prefetch entire video on any device.
480p 700 kbps ~126 MB Safe on desktop/tablet. Add memory check on mobile.
720p 1 000 kbps ~180 MB Fine for episodes. Skip on mobile with < 1 GB RAM available.
1080p 2 500 kbps ~450 MB Use endTime to cap to first 20 min on constrained devices.
4K / 2160p 8 000 kbps ~1.4 GB Full prefetch only on desktop/TV. Always use endTime on mobile.
javascript quality-aware, device-safe prefetch
hls.on(Hls.Events.MANIFEST_PARSED, function() {
  var level    = hls.levels[hls.currentLevel >= 0 ? hls.currentLevel : 0];
  var durS     = level.details ? level.details.totalduration : 0;
  var estMB    = (level.bitrate / 8 / 1e6) * durS;
  var isMobile = /Mobi|Android/i.test(navigator.userAgent);

  var opts = { concurrency: isMobile ? 3 : 6 };

  if (estMB > 1000 || (isMobile && estMB > 400)) {
    // 4K or large file on mobile  prefetch intro-skip zone only
    opts.endTime = 300;
  } else if (estMB > 400) {
    // 1080p  prefetch first 20 min to cover likely seek range
    opts.endTime = 1200;
  }
  // 720p and below: prefetch everything  fits comfortably in RAM

  hls.wsphls(opts);
  video.play();
});
Tip: The live demo's wsphls mode row lets you test default, level: N, and allLevels on any stream. Use the quality preset buttons in the cost calculator above to see how each quality tier affects CDN egress before choosing your strategy.

hls.wsphls( options )

METHOD hls.wsphls( options? ) → Promise<Result>

Prefetches all HLS segments for the current level into window.__hlsSegmentCache. Once the Promise resolves, a CacheFirstLoader is installed and buffer limits are set to effectively infinite the browser never enters a "waiting" state on seek because all data is already in the SourceBuffer.

If the manifest has not yet been loaded when wsphls() is called, it automatically waits for the LEVEL_LOADED event before starting.

alias hls.prefetchAllSegments() is identical.

What happens after the Promise resolves

1
CacheFirstLoader installed
Set as hls.config.fLoader. All future fragment requests are served from __hlsSegmentCache at zero network cost. Falls back to real network only on a cache miss.
2
Buffer limits maximized
maxBufferLength, maxMaxBufferLength, and backBufferLength are all set to 86400 (24 h). hls.js will eagerly append the entire video content into the SourceBuffer.
3
startLoad() triggered
Kicks hls.js to immediately start filling the buffer at the current playhead position, taking advantage of the new limits.

hls.prefetchAllSegments( options )

ALIAS hls.prefetchAllSegments( options? ) → Promise<Result>

Exact alias of hls.wsphls(). Accepts the same options and returns the same Promise. Use whichever name you prefer.

javascript
hls.prefetchAllSegments({ concurrency: 4 }).then(function(r) {
  console.log(r.prefetched + ' / ' + r.total + ' segments cached');
});

hls.help()

METHOD hls.help() → string

Logs the tutorial URL to the console and returns it as a string.

javascript
hls.help(); 
// logs: "wsphls help: see tutorial at https://wsphls-tutorial-2.pages.dev/"
// returns: "https://wsphls-tutorial-2.pages.dev/"

wsphls() Options

All options are optional. Pass as a plain object.

Option Type Default Description
concurrency number 6 Number of parallel fetch workers. Higher values speed up prefetch but increase bandwidth burst. Falls back to hls.config.prefetchConcurrency if set.
includeAudio boolean false Also prefetch segments from alternate audio tracks. Falls back to hls.config.prefetchIncludeAudio.
includeSubtitles boolean false Also prefetch subtitle track segments. Falls back to hls.config.prefetchIncludeSubtitles.
allLevels boolean false Prefetch segments from every quality level. When false, only the current (or first) level is prefetched.
level number null Force prefetch of a specific quality level by index (0 = lowest, higher indices = higher qualities). When set, overrides the current ABR level selection. Ignored if allLevels is true.
maxRetry number 2 How many times to retry a failed segment fetch before recording it in result.failed.
startTime number null Only prefetch segments whose end time is after this value (seconds). Useful for prefetching a clip range.
endTime number null Only prefetch segments whose start time is before this value (seconds).
onProgress function undefined Called after each segment is fetched with { prefetched, total, failed }. Use to drive a progress bar.
onError function undefined Called with (segment, error) when a segment fails after all retries. Does not abort the prefetch.

Config Options (new Hls({...}))

These can be set in the Hls constructor config object as defaults for wsphls(). Per-call options override these.

Config Key Type Description
prefetchConcurrency number Default concurrency for wsphls(). Overridden by options.concurrency.
prefetchIncludeAudio boolean Default for includeAudio option.
prefetchIncludeSubtitles boolean Default for includeSubtitles option.
javascript
const hls = new Hls({
  prefetchConcurrency:      8,
  prefetchIncludeAudio:     true,
  prefetchIncludeSubtitles: false,
});
// Now hls.wsphls() defaults to concurrency 8 and includes audio tracks

How It Works

WSP-HLS has two phases: prefetch (background segment download) and serve (cache-first interception via config.loader + config.fLoader). Click any step to explore details.

Your App
Entry point
hls.wsphls()
called after MANIFEST_PARSED
fetch
WSP-HLS Engine
Step 1
Build Segment Queue
all levels + tracks
Step 2
Concurrency Pool
N parallel workers
Step 3
Install CacheFirstLoader
replaces hls.config.loader + fLoader
miss store
Storage & Network
In-memory Map
__hlsSegmentCache
window.Map shared across Hls instances
Network
CDN / Origin
fetched once, served from cache forever
Click any block above to see details
IN
wsphls() called
Triggered by your code after MANIFEST_PARSED. Accepts optional { concurrency, startTime, endTime, onProgress, maxRetry }.
1
Parse manifest & build queue
Reads hls.levels[currentLevel].details.fragments. Filters by startTime / endTime if provided. Deduplicates segments by cache key.
2
Compute cache key per segment
url + "|" + byteRangeStart + "-" + byteRangeEnd Uniquely identifies each byte-range sub-resource. Byte-range segments inside the same file get separate keys.
3
Already in cache?
YES cache hit
Count as prefetched. No network trip. Move to next segment immediately.
NO cache miss
Proceed to network fetch below.
4
fetch() with Range header
Sends Range: bytes=start-end for byte-range segments. Full segments use a plain GET. Retries up to maxRetry times on failure.
5
Store payload + fire onProgress
Writes { payload: ArrayBuffer, iv?: Uint8Array } into window.__hlsSegmentCache. Calls onProgress({ prefetched, total }) for progress bar rendering.
OUT
Promise resolves CacheFirstLoader installed
Returns { prefetched, total, failed[] }. CacheFirstLoader is set as both hls.config.loader and hls.config.fLoader both must be replaced so hls.js picks up the cache loader for every new request. Buffer limits are maximized. hls.startLoad() is called.
IN
hls.js requests a fragment
Standard buffer management triggers a fragment load. The request is intercepted by CacheFirstLoader before any network call is made.
1
Compute cache key
Same formula: url + "|" + byteRangeStart + "-" + byteRangeEnd. Looked up in window.__hlsSegmentCache.
2
Cache hit or miss?
HIT
Returns ArrayBuffer via setTimeout(0). Zero latency. Restores iv for AES-128 streams. Calls callbacks.onSuccess.
MISS
Delegates to DefaultLoader for a normal network fetch. Covers init segments and anything outside the prefetch window.
OUT
hls.js receives data appends to SourceBuffer
The response is identical to a normal network response from hls.js's perspective. Buffer fills instantly. The HTMLVideoElement can seek with no buffering spinner.
Standard hls.js seek
1
User scrubs to timestamphls.js flushes current buffer
2
Segment not in bufferNetwork request fired to CDN
3
Waiting for CDN responseBuffering spinner shown 50–500 ms
4
Data arrives, buffered, playsTotal delay: 50–500 ms per seek
50–500 ms latency every seek
WSP-HLS seek (after prefetch)
1
User scrubs to timestamphls.js flushes current buffer
2
CacheFirstLoader interceptsReturns ArrayBuffer from memory
3
Data in SourceBuffer instantlyNo network wait, no spinner
4
Video plays immediatelyTotal delay: <5 ms (JS overhead only)
<5 ms zero network wait

Phase 2 detail cache hit & miss

Cache hit: Returns the ArrayBuffer synchronously via setTimeout(0) with zero network latency. Restores IV for encrypted streams.
Cache miss: Falls through to the original DefaultLoader for a normal network fetch. This covers init segments or anything not prefetched.

Segment Cache window.__hlsSegmentCache

All cached segments live in a single shared Map at window.__hlsSegmentCache (or self.__hlsSegmentCache in workers). This means:

javascript
// Inspect cache after prefetch
const cache = window.__hlsSegmentCache;
console.log('Cached segments:', cache.size);

// Estimated memory usage (bytes)
let totalBytes = 0;
cache.forEach(function(v) {
  totalBytes += v.payload ? v.payload.byteLength : 0;
});
console.log('~' + (totalBytes / 1024 / 1024).toFixed(1) + ' MB in memory');

// Clear the cache to free memory
window.__hlsSegmentCache.clear();

CacheFirstLoader

Installed automatically after wsphls() resolves as both hls.config.loader and hls.config.fLoader. Implements the full hls.js loader interface.

Method / Property Description
stats Read-only property returning the loader stats object. Synced to the inner DefaultLoader on cache miss.
load(context, config, callbacks) Checks the cache. On hit: calls callbacks.onSuccess via setTimeout(0). On miss: delegates to DefaultLoader.
abort() Aborts the inner DefaultLoader if a network request is in flight.
destroy() Destroys and nulls the inner DefaultLoader.
You don't need to interact with CacheFirstLoader directly. It is created and installed by wsphls() automatically. Installation is guarded by hls.__wsphlsCacheInstalled so it only runs once per instance, regardless of what config.fLoader is set to. Both hls.config.loader and hls.config.fLoader are replaced this is required because hls.js reads config.loader when constructing new loader instances at request time; setting only fLoader has no effect after the instance is already running.

Example: Basic Embed

Minimal full-page video player with prefetch.

html
<video id="v" controls style="width:100%"></video>
<script src="https://cdn.jsdelivr.net/gh/Tsukinatsune/CDN-Javascript-project@main/hlsv2.31.js"></script>
<script>
  var video = document.getElementById('v');
  if (Hls.isSupported()) {
    var hls = new Hls();
    hls.loadSource('https://example.com/video.m3u8');
    hls.attachMedia(video);
    hls.on(Hls.Events.MANIFEST_PARSED, function() {
      hls.wsphls(); // fire and forget
      video.play();
    });
  }
</script>

Example: Progress Bar

Show prefetch progress to the user with the onProgress callback.

html
<video id="video" controls></video>
<div id="bar-wrap" style="background:#eee;height:4px;border-radius:2px">
  <div id="bar" style="background:#2563eb;height:100%;width:0;transition:width 0.2s"></div>
</div>
<p id="label">Buffering segments…</p>

<script>
  var hls = new Hls();
  hls.loadSource('https://example.com/video.m3u8');
  hls.attachMedia(document.getElementById('video'));

  hls.on(Hls.Events.MANIFEST_PARSED, function() {
    hls.wsphls({
      concurrency: 8,
      onProgress: function(p) {
        var pct = (p.prefetched / p.total * 100).toFixed(0);
        document.getElementById('bar').style.width = pct + '%';
        document.getElementById('label').textContent =
          pct + '% cached (' + p.failed + ' failed)';
      }
    }).then(function() {
      document.getElementById('label').textContent = ' Fully cached  instant seeks enabled';
    });
  });
</script>

Example: Time Range Prefetch

Only prefetch the first 5 minutes of a long stream (segments 0 – 300 s).

javascript
hls.wsphls({
  startTime: 0,
  endTime:   300, // prefetch first 5 minutes only
  concurrency: 6,
  onProgress: function(p) {
    console.log(p.prefetched + '/' + p.total);
  }
}).then(function(r) {
  console.log('Clip prefetch done', r);
});
A segment is included if its end time is after startTime AND its start time is before endTime. Segments that overlap the boundary are included.

Example: Encrypted Streams (AES-128)

No special setup needed. The CacheFirstLoader automatically restores the IV from the cached entry on cache hits, so encrypted streams decrypt correctly after prefetch.

javascript
// AES-128 encrypted stream  works as-is
var hls = new Hls();
hls.loadSource('https://example.com/encrypted/playlist.m3u8');
hls.attachMedia(video);

hls.on(Hls.Events.MANIFEST_PARSED, function() {
  // wsphls() caches segments; IV preserved automatically
  hls.wsphls({ concurrency: 4 }).then(function(r) {
    console.log('Encrypted stream fully cached', r);
  });
  video.play();
});

Promise Result Object

The Promise returned by wsphls() resolves with:

Result shape
{ prefetched: number, total: number, failed: Array<{url, error}> }
FieldTypeDescription
prefetched number Total segments successfully fetched or already in cache.
total number Total segments in the queue (before dedup). Does not count segments that were already cached before the call.
failed Array Segments that failed after all retries. Each item: { url: string, error: string }. Empty array on full success.
javascript
hls.wsphls().then(function(result) {
  console.log(result.prefetched); // e.g. 120
  console.log(result.total);      // e.g. 120
  console.log(result.failed);     // []  or [{ url, error }]

  if (result.failed.length > 0) {
    console.warn('Some segments failed:', result.failed);
  }
});

Key HLS Events

Standard hls.js events most commonly used alongside wsphls().

EventWhen to use with wsphls()
MANIFEST_PARSED Best place to call wsphls() levels are available but no segments fetched yet.
LEVEL_LOADED wsphls() waits for this internally if called before manifest is loaded.
FRAG_LOADED Fires for each segment hls.js loads during normal playback.
ERROR Network or decode errors handle separately from wsphls()'s onError.
javascript
hls.on(Hls.Events.MANIFEST_PARSED, function(event, data) {
  console.log('Levels:', data.levels.length);
  hls.wsphls();
});

hls.on(Hls.Events.ERROR, function(event, data) {
  if (data.fatal) {
    console.error('Fatal HLS error:', data.type, data.details);
    hls.destroy();
  }
});

Browser Support

Check support at runtime with Hls.isSupported(). This build supports Chrome, Edge, Firefox, Safari (desktop & iOS) Hls.isSupported() returns true on iOS with this build, so wsphls() works there too.