@copperdesign/lazy-video-backgrounds
v0.2.0
Published
Sequentially-looping background-video playlist with progressive lazy loading and pause-when-offscreen.
Downloads
208
Maintainers
Readme
@copperdesign/lazy-video-backgrounds
Sequentially-looping background-video playlist with progressive lazy loading and pause-when-offscreen.
Drop a row of <video> elements into a container, point this at the container, and they'll play one at a time, loop the current one while the next buffers, and pause automatically when you scroll away. No framework. No build step. ~1 KB minified.
<div id="hero">
<video preload="none" poster="clip-1.jpg" muted playsinline>
<source src="clip-1.mp4" type="video/mp4">
</video>
<video preload="none" poster="clip-2.jpg" muted playsinline>
<source src="clip-2.mp4" type="video/mp4">
</video>
<video preload="none" poster="clip-3.jpg" muted playsinline>
<source src="clip-3.mp4" type="video/mp4">
</video>
</div>
<script type="module">
import lazyVideoBackgrounds from '@copperdesign/lazy-video-backgrounds';
lazyVideoBackgrounds(document.getElementById('hero'));
</script>That's the whole API.
What it does
- Plays one clip at a time. Children of the root are taken in DOM order.
- Lazy-loads the rest. When a clip starts, only the next one is told to buffer (its
preloadraised toauto, thenload()), so by the time the current finishes, the next is ready — and clips further down download nothing until their turn. - Loops the current while next is still buffering. No black-frame stalls. Once the next is ready, it takes over on the following
ended. - Pauses when offscreen. An
IntersectionObserveron the root pauses the active video when it scrolls out of view and resumes when it scrolls back in. - Tags state in CSS. The currently-active video gets
.is-playingor.is-paused— use these in your own styles for fades, overlays, etc.
Install
npm install @copperdesign/lazy-video-backgroundsOr vendor index.js directly — it's a single file with no dependencies.
API
import lazyVideoBackgrounds from '@copperdesign/lazy-video-backgrounds';
const teardown = lazyVideoBackgrounds(root, options);root
The container element. Its direct <video> children are the playlist. Non-video children are ignored, so you can sprinkle in overlays, captions, etc.
options
| Option | Default | Description |
|---|---|---|
| autoplay | true | Pick a starting clip and play it on init. Set false to take over playback control yourself. |
| random | true | Starting clip is random. Set false to start at the first child. |
| pauseWhenOffscreen | true | Pause the active video when the root scrolls out of the viewport. |
| classNames.playing | 'is-playing' | Class added to the active, playing video. |
| classNames.paused | 'is-paused' | Class added to the active, paused video. |
Return value
A teardown() function. Call it to remove every event listener and disconnect the observer — useful in SPAs when the host element is unmounted.
const teardown = lazyVideoBackgrounds(root);
// ...later
teardown();Markup recommendations
- Use
preload="none"and aposteron every video. Withpreload="auto", current Chromium, Firefox and WebKit buffer every clip at once — five clips, five downloads, before the first has finished. Withnone, nothing downloads until a clip is about to play: the module starts the first, and raises the next one'spreloadtoautoas each clip begins. The poster (the clip's first frame) fills the gap while the first clip loads, and stays as the still frame if playback never starts. preload="auto"still works — the playlist behaves the same, it just costs every clip's bytes on page load.- Use
mutedandplaysinline— without them, mobile and autoplay policies will rejectplay(). - Don't put
loopon the videos. The script chains them onended;loopwould prevent that event from firing. - List the smaller format first. The browser takes the first
<source>it can play.
<video preload="none" poster="clip.jpg" muted playsinline>
<source src="clip.webm" type='video/webm; codecs="vp9"'>
<source src="clip.mp4" type="video/mp4">
</video>CSS hooks
The currently active video carries .is-playing or .is-paused. Stack the videos absolutely, default them to opacity: 0, and fade in the playing one:
#hero { position: relative; }
#hero video {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
object-fit: cover;
opacity: 0;
transition: opacity 200ms ease-out;
}
#hero video.is-playing { opacity: 1; }Why this exists
A common hero pattern: several short clips that play back-to-back as a moving background. The naive implementation — five <video> tags and a sequencer that swaps them on ended — falls into two traps:
preloadis a hint, and both ends of it hurt. Withpreload="auto", browsers buffer every clip on page load, whether it plays in five seconds or never. Withpreload="none", a clip that hasn't been played sits atreadyState 0— and evenload()may not move it past "can play" (Firefox honoursnoneafterload()). The naive sequencer either downloads everything up front or waits for acanplaythroughthat never comes.canplaythroughis a fire-and-forget event. If it fires before your handler attaches (a real race with small clips), you'll never observe it.
This module fixes both: it seeds readiness from readyState and listens for the event, and when a clip starts playing it raises the next clip's preload to auto and calls load() — so exactly one clip buffers ahead.
Contributing
PRs and issues welcome. See CONTRIBUTING.md for setup, the PR workflow, and what fits the scope of the module. The repo follows the Contributor Covenant.
Quick version: fork, branch off main, exercise your change against
example.html in at least one non-Chromium browser, open a PR. I
(@copperdesign) review and merge.
Releasing (maintainer notes)
The package is published to npm as
@copperdesign/lazy-video-backgrounds
and installable in any project with:
npm install @copperdesign/lazy-video-backgroundsFor future releases:
npm version patch # or minor / major — bumps package.json, commits, tags vX.Y.Z
git push --follow-tags
gh release create vX.Y.Z --generate-notesThe release.yml GitHub Actions workflow handles the rest: it smoke-checks
the module, verifies the tag matches package.json, and publishes to npm
with provenance. It authenticates through npm Trusted Publishing (OIDC),
so there is no token to rotate; the trusted publisher is configured on the
package's settings page on npmjs.com.
License
MIT — see LICENSE.
Created by Christian Fillies.
