web-vitals-lite
v0.1.0
Published
Tiny Core Web Vitals measurement wrapper — LCP, CLS, and INP via PerformanceObserver, with an injectable observer for testing.
Maintainers
Readme
web-vitals-lite
Tiny Core Web Vitals measurement wrapper (LCP, CLS, INP) built directly on PerformanceObserver, with an injectable observer factory so the logic is fully unit-testable without a real browser.
Install
npm install web-vitals-liteQuick start
import { observeLCP, observeCLS, observeINP } from 'web-vitals-lite';
const createObserver = (cb) => {
const obs = new PerformanceObserver((list) => cb(list.getEntries()));
return obs;
};
observeLCP((metric) => sendToAnalytics(metric), createObserver);
observeCLS((metric) => sendToAnalytics(metric), createObserver);
observeINP((metric) => sendToAnalytics(metric), createObserver);Why an injectable observer factory
PerformanceObserver only exists in browsers, which normally means these functions can't be unit-tested without a headless browser or heavy mocking of globals. Taking the observer as a parameter — (callback) => PerformanceObserver-shaped — means the actual reporting logic (running max for LCP, accumulator for CLS, running max duration for INP) can be tested with a plain fake object, and the real PerformanceObserver wiring is one line at the call site.
API
observeLCP(onReport, createObserver)— reports the largest LCP candidate seenobserveCLS(onReport, createObserver)— reports the running CLS total (ignoring input-triggered shifts)observeINP(onReport, createObserver)— reports the worst interaction duration seen
All three return the underlying observer so you can .disconnect() it.
License
MIT
