TL;DR
Most players time startup from
play()toplaying. That skips everything your app does between the click andplay(). We'll build a smalltrackStartup()helper that starts at the click, ends on the first presented frame viarequestVideoFrameCallback, splits the time into phases, and reports viewers who left before a frame showed. Tested with Playwright 1.63.0 and Chromium 153.📦 Code: github.com/USER/repo (replace before publishing)
What we're measuring ⏱️
click -> app work (mount, fetch URL/token) -> play() -> metadata -> first frame
|<------------------- what the viewer waits for ------------------------------>|
|<- what most dashboards record ->|
Setup: Node 22, npm i -D playwright, and a test clip. Playwright's Chromium does not ship H.264, so use VP9:
ffmpeg -f lavfi -i testsrc2=size=1280x720:rate=30:duration=10 \
-c:v libvpx-vp9 -b:v 1M -g 60 clip.webm
1. A server that can be slow on purpose
To see startup phases we need latency we control. This static server supports range requests and a ?delay= parameter:
// server.mjs
import http from 'node:http';
import fs from 'node:fs';
import path from 'node:path';
const types = { '.html': 'text/html', '.webm': 'video/webm', '.js': 'text/javascript' };
http.createServer((req, res) => {
const url = new URL(req.url, 'http://x');
const file = path.join(process.cwd(), url.pathname);
if (!fs.existsSync(file)) { res.writeHead(404); return res.end(); }
const size = fs.statSync(file).size;
const delay = Number(url.searchParams.get('delay') || 0);
const m = /bytes=(\d+)-(\d*)/.exec(req.headers.range || '');
const start = m ? Number(m[1]) : 0;
const end = m && m[2] ? Number(m[2]) : size - 1;
setTimeout(() => {
res.writeHead(m ? 206 : 200, {
'Content-Type': types[path.extname(file)] || 'application/octet-stream',
'Accept-Ranges': 'bytes', 'Content-Length': end - start + 1,
...(m ? { 'Content-Range': `bytes ${start}-${end}/${size}` } : {}),
});
fs.createReadStream(file, { start, end }).pipe(res);
}, delay);
}).listen(8080, () => console.log('http://localhost:8080'));
2. First, is playing good enough as the end mark?
Before building anything, I checked how far playing is from the first frame actually handed to the compositor. requestVideoFrameCallback gives us metadata.presentationTime for that. Clock starts at play(), preload="none":
delay=0ms {"loadedmetadata":11,"frame_presented":32,"playing":46}
delay=400ms {"loadedmetadata":414,"frame_presented":421,"playing":435}
delay=1500ms {"loadedmetadata":1512,"frame_presented":1520,"playing":1537}
(Trimmed to the three fields that matter. Milliseconds. One machine, headless, localhost, so read the shape and not the values.)
playing landed about 15 ms after the first presented frame every time. So the end mark is not the problem. We'll use the frame callback where it exists and playing as the fallback. requestVideoFrameCallback is Baseline since October 2024 per MDN.
3. The startup timer 🛠️
// startup-timer.js: measure video startup from user intent, not from play()
export function trackStartup(video, { intentAt = performance.now(), onReport }) {
const marks = { intent: 0 };
const mark = (name, t = performance.now()) => {
if (!(name in marks)) marks[name] = Math.round(t - intentAt);
};
let done = false;
const preloaded = video.readyState >= HTMLMediaElement.HAVE_CURRENT_DATA;
const finish = (outcome) => {
if (done) return;
done = true;
document.removeEventListener('visibilitychange', onHide);
onReport({ outcome, preloaded, ...marks });
};
const onHide = () => { if (document.visibilityState === 'hidden') finish('abandoned'); };
document.addEventListener('visibilitychange', onHide);
video.addEventListener('play', () => mark('play_called'), { once: true });
video.addEventListener('loadedmetadata', () => mark('metadata'), { once: true });
video.addEventListener('playing', () => mark('playing'), { once: true });
video.addEventListener('error', () => finish('error'), { once: true });
const onFrame = (now, meta) => {
// A preloaded video has already painted frame 1. Wait for a frame that advanced.
if (preloaded && meta.mediaTime === 0) return video.requestVideoFrameCallback(onFrame);
mark('first_frame', meta.presentationTime);
finish('started');
};
if ('requestVideoFrameCallback' in video) video.requestVideoFrameCallback(onFrame);
else video.addEventListener('playing', () => { mark('first_frame'); finish('started'); }, { once: true });
}
What each piece is for:
-
intentAtis passed in. The caller captures it in the click handler, before any async work. -
{ once: true }onplayingmatters. MDN notesplayingfires again whenever playback restarts after a pause or a stall. Withoutonceyou would overwrite startup with a rebuffer. -
preloadedis recorded so you can split cold starts from warm ones later. -
abandonedfires when the tab is hidden before a frame shows. Those sessions never appear in a metric that only records successful starts.
4. Use it from a click handler
<!-- app.html -->
<!doctype html>
<button id="watch">Watch</button>
<video id="v" playsinline muted width="640"></video>
<script type="module">
import { trackStartup } from './startup-timer.js';
const q = new URLSearchParams(location.search);
const api = Number(q.get('api') || 0), media = Number(q.get('media') || 0);
const video = document.getElementById('v');
if (q.has('preload')) { video.preload = 'auto'; video.src = `clip.webm?delay=${media}`; }
document.getElementById('watch').addEventListener('click', async () => {
const intentAt = performance.now(); // the clock starts at the click
trackStartup(video, { intentAt, onReport: (r) => { window.report = r; } });
await new Promise((r) => setTimeout(r, api)); // stand-in for "fetch playback URL / token"
if (!video.src) video.src = `clip.webm?delay=${media}`;
await video.play();
});
</script>
The api query parameter fakes the request your app makes before it has a playback URL. In production, replace window.report = r with a beacon:
// report.js
onReport: (r) => navigator.sendBeacon('/qoe/startup', JSON.stringify(r)),
sendBeacon is the right call here because the abandoned case fires while the page is going away.
5. Run it under four conditions
// startup.test.mjs
import { chromium } from 'playwright';
const browser = await chromium.launch();
for (const qs of ['?api=0&media=0', '?api=300&media=400', '?api=300&media=400&preload']) {
const page = await browser.newPage();
await page.goto('http://localhost:8080/app.html' + qs);
await page.waitForTimeout(1500);
await page.click('#watch');
const r = await (await page.waitForFunction(() => window.report)).jsonValue();
console.log(qs.padEnd(32), JSON.stringify(r));
await page.close();
}
// abandoned start: the viewer leaves before the first frame
const page = await browser.newPage();
await page.goto('http://localhost:8080/app.html?api=300&media=3000');
await page.click('#watch');
await page.waitForTimeout(800);
await page.evaluate(() => {
Object.defineProperty(document, 'visibilityState', { value: 'hidden', configurable: true });
document.dispatchEvent(new Event('visibilitychange'));
});
console.log('leave at 800ms'.padEnd(32), JSON.stringify(await page.evaluate(() => window.report)));
await browser.close();
$ node server.mjs & node startup.test.mjs
?api=0&media=0 {"outcome":"started","preloaded":false,"intent":0,"play_called":16,"metadata":32,"playing":69,"first_frame":59}
?api=300&media=400 {"outcome":"started","preloaded":false,"intent":0,"play_called":303,"metadata":712,"playing":734,"first_frame":718}
?api=300&media=400&preload {"outcome":"started","preloaded":true,"intent":0,"play_called":301,"playing":301,"first_frame":359}
leave at 800ms {"outcome":"abandoned","preloaded":false,"intent":0,"play_called":304}
6. Reading the output
| Row | What it tells us |
|---|---|
api=300&media=400 |
First frame at 718 ms from the click. A play() to playing timer would report 734 minus 303, so 431 ms, for the same session. The 303 ms before play() is your app, and it was invisible. |
preload |
playing fires the instant play() is called (301 ms), because a frame was already decoded. The first frame that advanced came at 359 ms. Don't average this with cold starts. |
leave at 800ms |
No first_frame, outcome abandoned. This viewer waited 800 ms and saw nothing. A success-only metric would have no row for them. |
The phase split falls out of the marks:
-
play_calledminusintentis application time: bundle, mount, API calls. -
metadataminusplay_calledis the network getting the first useful bytes. -
first_frameminusmetadatais buffering and decode.
💡 Tip: When startup regresses, look at which of those three grew before anyone opens a CDN dashboard.
Things to know
-
Carry intent across routes. If the click navigates to a watch page inside a single-page app, stash
performance.now()at click time (module variable or router state) and pass it asintentAtafter mount. For autoplay on a fresh page load, use0, which is navigation start on theperformance.now()timeline. -
hls.js and other MSE players work with this as written, since the marks come from the
<video>element. Add your own mark for manifest loaded if you want a fourth phase. -
Background tabs. Frame callbacks are tied to rendering. A tab opened in the background may not report a frame until it is visible, which is another reason to keep
playingin the record. -
loadeddatais not a display signal. MDN notes it may not fire at all on mobile with data saver on. Don't end the clock there. -
Report percentiles. Send raw rows and compute p50, p75 and p95 server side, split by
preloaded, with theabandonedcount beside them.
What's next
- Add a
stalled_mscounter usingwaitingandplayingpairs after startup. You already have the listeners in place, and it gives you rebuffer time with the same beacon. - Run the harness against your real watch page with the click as the start mark, and compare with what your current analytics say for the same session. The difference is the part of startup you have not been measuring.
Top comments (0)