# lazy-video

Video media that picks the media component for its source and loads only that component's code

> **Caution: Unstable API**
>
> This API works today, but its shape is still settling and may change in a minor release. The implementation underneath is production quality; what is not final is how you configure it from Video.js. Pin your version and check the changelog when you upgrade.

Reads `src`, renders the media component that plays it, and loads that component’s code only once the source is known. A page playing an MP4 loads no engine; a page playing DASH loads dash.js and nothing else.

## Import

```bash
npm install @videojs/html @videojs/hlsjs-video @videojs/dash-video @videojs/mux-video @videojs/youtube-video @videojs/vimeo-video @videojs/wistia-video @videojs/cloudflare-video @videojs/tiktok-video @videojs/playerjs-video
```

```ts
import '@videojs/html/media/lazy-video';
```

Install every engine package listed: your bundler resolves each media component `LazyVideo` can load, so a missing one fails the build. Each engine still lands in its own chunk, which downloads only when a source needs it. To install fewer, [build your own](#custom-media) from just the media you need.

## Sources

| Source | Resolves to | Loads |
| --- | --- | --- |
| `.mp4`, `.webm`, `.mov`, `.ogv`, and audio files | Native `<video>` | Nothing |
| HLS | [HlsJsVideo](https://videojs.org/docs/framework/html/reference/components/hlsjs-video) | hls.js |
| HLS where there’s no MSE | [NativeHlsVideo](https://videojs.org/docs/framework/html/reference/components/native-hls-video) | Native HLS support |
| `stream.mux.com` | [MuxVideo](https://videojs.org/docs/framework/html/reference/components/mux-video) | Mux Video |
| DASH (`.mpd`) | [DashVideo](https://videojs.org/docs/framework/html/reference/components/dash-video) | dash.js |
| YouTube | [YouTubeVideo](https://videojs.org/docs/framework/html/reference/components/youtube-video) | The YouTube embed |
| Vimeo | [VimeoVideo](https://videojs.org/docs/framework/html/reference/components/vimeo-video) | The Vimeo embed |
| Wistia | [WistiaVideo](https://videojs.org/docs/framework/html/reference/components/wistia-video) | The Wistia player |
| Cloudflare Stream | [CloudflareVideo](https://videojs.org/docs/framework/html/reference/components/cloudflare-video) | The Cloudflare Stream embed |
| TikTok | [TikTokVideo](https://videojs.org/docs/framework/html/reference/components/tiktok-video) | The TikTok embed |
| player.js embeds marked with `?playerjs` | [PlayerJsVideo](https://videojs.org/docs/framework/html/reference/components/playerjs-video) | The service’s player.js embed |

Sources are matched by the hosts and shorthands [`resolveAdapterType`](https://videojs.org/docs/framework/html/reference/api/resolve-adapter-type) recognizes, then by MIME type or file extension. A media file on one of these hosts, such as a direct Vimeo MP4, plays as that file. A source that matches none of these renders nothing and logs an error in development.

player.js is a protocol any embed can speak, so nothing in an embed’s URL says it’s one. Add a `playerjs` query parameter to choose the player.js media, such as `https://streamable.com/e/moo?playerjs`. It takes precedence over the host and file extension, and the player.js media removes it before loading the embed.

## Behavior

The media component starts loading as soon as `src` is set. It doesn’t wait for the player to scroll into view. The resolved media plays with `preload="none"` unless you set `preload` yourself.

Changing `src` to a source the same media plays updates that media in place. Changing it to a source that needs a different media replaces the media once the new one has loaded.

Until the media loads, nothing is rendered in its place, so give the player an aspect ratio, as the installation snippet does, and its box stays the same size while the media loads and when `src` swaps it for another. Without one, the player takes its height from the media once it renders.

Set `type` to the source’s MIME type when its URL has no file extension, such as a signed URL. `type` only chooses the media; it isn’t passed on.

Set `source` instead of `src` to give the media its structured source, with options beyond the URL. Its `src` and `type` choose the media as `src` and `type` do, and a Mux `playbackId` or a Wistia `mediaId` chooses the Mux or Wistia media without a URL. The resolved media takes the whole object as its `source`; a native `<video>` takes only its `src`. While `source` is set, `src` and `type` are ignored.

```js
document.querySelector('lazy-video').source = { playbackId: 'a4nOgmxGWg6gULfcBbAa00gXyfcwPnAFldF8RdsNyk8M' };
```

HLS plays through hls.js wherever the browser has MSE, Safari included, so it has the same features everywhere. Only a browser without MSE, such as iOS before 17.1, plays it natively. Set `preferPlayback` to `'native'` to play HLS natively wherever the browser can, or to `'mse'` to always play it through hls.js. It’s also passed on to the resolved hls.js or Mux media, on its `source`, so a Mux stream follows the same preference.

Every other attribute, except `id`, `class`, `style`, `slot`, and `part`, is copied to the resolved media element, which `<lazy-video>` renders as its child. `<track>` and `<source>` children present when the media is created move into it; add later ones to the media element directly. `<lazy-video>` lays out as its child does, so a skin sizes it the same way as the element it resolves to. An embed fills the player, and falls back to 16:9 in a player with no height of its own.

## Custom media

`createLazyVideoElement` builds a `<lazy-video>` class from a list of media, tried in order, to register under a tag of your own. Each built-in media has its own import, so the list decides which engine packages need to be installed. Put your own media first to take sources from the built-in ones.

```ts
import { createLazyVideoElement } from '@videojs/html/media/lazy/create';
import { hlsjsVideo } from '@videojs/html/media/lazy/hlsjs-video';
import { nativeHlsVideo } from '@videojs/html/media/lazy/native-hls-video';
import { video } from '@videojs/html/media/lazy/video';

customElements.define(
  'acme-lazy-video',
  createLazyVideoElement([
    {
      match: ({ url }) => url?.hostname === 'video.acme.com',
      tag: 'acme-video',
      load: () => import('./acme-video'),
    },
    video,
    nativeHlsVideo,
    hlsjsVideo,
  ])
);
```

A media gives `match`, the `tag` of the element that plays its sources, and `load` to register that element once a source needs it. Leave `load` out for an element that’s built in or already registered. Set `preferPlayback: true` when the element takes `preferPlayback` on its `source`, as `<hlsjs-video>` and `<mux-video>` do.

`match` receives the source worked out once for every media:

| Field | Type | Description |
| --- | --- | --- |
| `src` | `string` | The trimmed source URL; empty for a structured source that names its media by id. |
| `type` | `string \| undefined` | The MIME type the source was given. |
| `url` | `URL \| null` | `src` parsed as a URL, or `null` for a path or bare id. |
| `adapterType` | `AdapterType \| null` | The kind of source, with the names [`resolveAdapterType`](https://videojs.org/docs/framework/html/reference/api/resolve-adapter-type) returns, such as `'hls'` or `'youtube'`. |
| `playback` | `'native' \| 'mse' \| undefined` | How HLS should play here, after `preferPlayback`. `undefined` while it isn’t known, such as during server rendering. |
| `source` | `LazyMediaSource \| null` | The structured `source` it was resolved from, if any, for media that match on more than the URL. |

Return `true` to play the source, or `undefined` when the media can’t tell yet; it isn’t chosen until it can, and nothing after it is tried.

The built-in media are `video`, `nativeHlsVideo`, `hlsjsVideo`, `dashVideo`, `muxVideo`, `youtubeVideo`, `vimeoVideo`, `wistiaVideo`, `cloudflareVideo`, `tiktokVideo`, and `playerJsVideo`, each imported from `media/lazy/` plus its kebab-case name.

## Lazy loading one known media

`LazyVideo` is for sources you don’t know ahead of time. When you already know which media plays the source, load that media’s own entry lazily instead: no source matching, and only its code.

Write the media element in the page, and import its module when you want it to load:

```html
<video-player>
  <video-skin>
    <vimeo-video src="https://vimeo.com/76979871"></vimeo-video>
  </video-skin>
</video-player>
```

```ts
import('@videojs/html/media/vimeo-video');
```

The import defines `<vimeo-video>`, and the browser upgrades the element in place: it reads the attributes already on it and registers with the player. Set attributes rather than properties before the import; a property set on an element that isn’t defined yet hides the element’s own property once it is.

Until the media loads, the player has no media, so its controls show their empty state.

## Examples

### Basic Usage

**index.html**

```html
<div class="html-lazy-video-basic">
  <lazy-video
    class="html-lazy-video-basic__media"
    src="https://stream.mux.com/BV3YZtogl89mg9VcNBhhnHm02Y34zI1nlMuMQfAbl3dM/highest.mp4"
    controls
    muted
    playsinline
  ></lazy-video>
  <div class="html-lazy-video-basic__sources">
    <button type="button" data-src="https://stream.mux.com/BV3YZtogl89mg9VcNBhhnHm02Y34zI1nlMuMQfAbl3dM/highest.mp4">MP4</button>
    <button type="button" data-src="https://stream.mux.com/BV3YZtogl89mg9VcNBhhnHm02Y34zI1nlMuMQfAbl3dM.m3u8">HLS</button>
    <button type="button" data-src="https://dash.akamaized.net/akamai/streamroot/050714/Spring_4Ktest.mpd">DASH</button>
    <button type="button" data-src="https://www.youtube.com/watch?v=aqz-KE-bpKQ">YouTube</button>
  </div>
</div>
```

**index.css**

```css
.html-lazy-video-basic {
  display: grid;
  gap: 12px;
  width: 100%;
}

/* `<lazy-video>` renders as its resolved media, so the box goes on its child. */
.html-lazy-video-basic__media > * {
  display: block;
  width: 100%;
  aspect-ratio: 16 / 9;
  background: #000;
}

.html-lazy-video-basic__sources {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}
```

**index.ts**

```ts
import '@videojs/html/media/lazy-video';

const lazyVideo = document.querySelector('.html-lazy-video-basic__media')!;

for (const button of document.querySelectorAll<HTMLButtonElement>('.html-lazy-video-basic__sources button')) {
  button.addEventListener('click', () => lazyVideo.setAttribute('src', button.dataset.src!));
}
```

## API Reference

| Attribute | Property | Type | Default | Description |
| --- | --- | --- | --- | --- |
| `src` | `src` | `string` | | Source URL. Its host or file extension chooses the media. |
| `type` | `type` | `string` | | MIME type of the source. Takes precedence over the file extension. |
| | `source` | `LazyMediaSource` | | Structured source, in place of `src` and `type`. Chooses the media by its `src`, `type`, `playbackId`, or `mediaId`, and is passed on as the media’s `source`. |
| `prefer-playback` | `preferPlayback` | `'native' \| 'mse'` | | Playback path for HLS: `'native'` wherever the browser can, `'mse'` always through hls.js. Unset, through hls.js wherever there’s MSE, and native only where there’s none. Also passed on to hls.js and Mux media. |
| `preload` | | `'none' \| 'metadata' \| 'auto' \| ''` | `'none'` | How much the resolved media loads before playback. |

---

HTML documentation: https://videojs.org/docs/framework/html/llms.txt
All documentation: https://videojs.org/llms.txt
