100Implement a performance monitor measuring Web Vitals and reporting metrics
mediumAbout 45 minutesCodingperformanceweb-vitalsperformance-observermonitoring
Problem
Measure Core Web Vitals from real users. Implement:
rate(name, value):"good","needs-improvement"or"poor"using these thresholds (good up to the first number, poor above the second): LCP 2500/4000 ms, INP 200/500 ms, CLS 0.1/0.25, FCP 1800/3000 ms, TTFB 800/1800 ms.computeCLS(entries): entries are{ value, startTime, hadRecentInput }. Ignore shifts withhadRecentInput. Group the rest into session windows: a window ends when there is a gap of more than 1,000 ms since the previous shift, or when it would span more than 5,000 ms. CLS is the largest window's sum.computeINP(durations): the durations of all interactions. With fewer than 50 interactions, INP is the longest; otherwise skip the single longest interaction per 50 (with 120 interactions, skip the 2 longest and take the next).createVitalsMonitor({ observe, report, doc = document, getNavigationEntry }):observe(type, callback)subscribes to performance entries of a type ("paint","largest-contentful-paint","layout-shift","event"); the default usesPerformanceObserverwithbuffered: true;- FCP is the
first-contentful-paintpaint entry'sstartTime; LCP is the latest LCP entry'sstartTime; event entries with the sameinteractionId(> 0) are one interaction whose duration is the longest of them; TTFB isgetNavigationEntry().responseStart; - when
doc.visibilityStatebecomes"hidden", callreport(metrics)with[{ name, value, rating }]for every metric that has a value and changed since the last report (do not callreportif nothing changed).
Try it yourself
Write your solution, run it, then submit to check it against the tests.
App.jsxReact + DOM
Step-by-step
Store [good, poor] thresholds per metric. value <= good is good, value <= poor needs improvement, anything above is poor.
Unlock the full solution
What's inside
- Step-by-step
- Approach
- Solution
- Complexity
- Edge cases
- Follow-up questions
- Tests
Includes 2 code listings, 5 edge cases, 4 follow-up questions.
One-time payment by UPI, card or net banking. Launch price.