Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Flush buffered vitals metrics on page mount #33867

Merged
merged 5 commits into from Feb 1, 2022
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
7 changes: 6 additions & 1 deletion packages/next/client/index.tsx
Expand Up @@ -33,7 +33,7 @@ import measureWebVitals from './performance-relayer'
import { RouteAnnouncer } from './route-announcer'
import { createRouter, makePublicRouterInstance } from './router'
import { getProperError } from '../lib/is-error'
import { trackWebVitalMetric } from './vitals'
import { flushBufferedVitalsMetrics, trackWebVitalMetric } from './vitals'
import { RefreshContext } from './rsc/refresh'

/// <reference types="react-dom/experimental" />
Expand Down Expand Up @@ -1011,6 +1011,11 @@ function Root({
React.useEffect(() => {
measureWebVitals(onPerfEntry)
}, [])

// Flush buffer on mount
React.useEffect(() => {
flushBufferedVitalsMetrics()
}, [])
huozhi marked this conversation as resolved.
Show resolved Hide resolved
return children as React.ReactElement
}

Expand Down
29 changes: 24 additions & 5 deletions packages/next/client/vitals.ts
Expand Up @@ -3,24 +3,43 @@ import { NextWebVitalsMetric } from '../pages/_app'

type ReportWebVitalsCallback = (webVitals: NextWebVitalsMetric) => any
export const webVitalsCallbacks = new Set<ReportWebVitalsCallback>()
const metrics: NextWebVitalsMetric[] = []

let flushed = false
export const bufferedVitalsMetrics: NextWebVitalsMetric[] = []
huozhi marked this conversation as resolved.
Show resolved Hide resolved

export function flushBufferedVitalsMetrics() {
flushed = true
bufferedVitalsMetrics.length = 0
}

export function trackWebVitalMetric(metric: NextWebVitalsMetric) {
metrics.push(metric)
bufferedVitalsMetrics.push(metric)
webVitalsCallbacks.forEach((callback) => callback(metric))
}

export function useWebVitalsReport(callback: ReportWebVitalsCallback) {
const metricIndexRef = useRef(0)

if (process.env.NODE_ENV === 'development') {
if (flushed) {
console.error(
`Web vitals reporting callback is attached too late, please attach it before page is mounted.`
huozhi marked this conversation as resolved.
Show resolved Hide resolved
)
}
}

useEffect(() => {
// Flush calculated metrics
const reportMetric = (metric: NextWebVitalsMetric) => {
callback(metric)
metricIndexRef.current = metrics.length
metricIndexRef.current = bufferedVitalsMetrics.length
}
for (let i = metricIndexRef.current; i < metrics.length; i++) {
reportMetric(metrics[i])
for (
let i = metricIndexRef.current;
i < bufferedVitalsMetrics.length;
i++
) {
reportMetric(bufferedVitalsMetrics[i])
}

webVitalsCallbacks.add(reportMetric)
Expand Down
3 changes: 3 additions & 0 deletions test/integration/relay-analytics-disabled/pages/index.js
@@ -1,3 +1,5 @@
import { bufferedVitalsMetrics } from 'next/dist/client/vitals'

if (typeof navigator !== 'undefined') {
window.__BEACONS = window.__BEACONS || []

Expand All @@ -20,6 +22,7 @@ export default () => {
<div>
<h1>Foo!</h1>
<h2>bar!</h2>
<p>{`buffered metrics: ${bufferedVitalsMetrics.length}`}</p>
</div>
)
}
Expand Up @@ -30,11 +30,13 @@ describe('Analytics relayer (disabled)', () => {
const browser = await webdriver(appPort, '/')
await browser.waitForElementByCss('h1')
const h1Text = await browser.elementByCss('h1').text()
const pText = await browser.elementByCss('p').text()
const firstContentfulPaint = parseFloat(
await browser.eval('localStorage.getItem("FCP")')
)

expect(h1Text).toMatch(/Foo!/)
expect(pText).toMatch('buffered metrics: 0')

expect(firstContentfulPaint).not.toBeNaN()
expect(firstContentfulPaint).toBeGreaterThan(0)
Expand Down
2 changes: 2 additions & 0 deletions test/integration/relay-analytics/pages/index.js
@@ -1,5 +1,6 @@
/* global localStorage */
import { unstable_useWebVitalsReport } from 'next/vitals'
import { bufferedVitalsMetrics } from 'next/dist/client/vitals'

if (typeof navigator !== 'undefined') {
window.__BEACONS = window.__BEACONS || []
Expand Down Expand Up @@ -37,6 +38,7 @@ export default () => {
<div>
<h1>Foo!</h1>
<h2>bar!</h2>
<p>{`buffered metrics: ${bufferedVitalsMetrics.length}`}</p>
</div>
)
}
2 changes: 2 additions & 0 deletions test/integration/relay-analytics/test/index.test.js
Expand Up @@ -67,6 +67,7 @@ function runTest() {
await browser.waitForElementByCss('h1')

const h1Text = await browser.elementByCss('h1').text()
const pText = await browser.elementByCss('p').text()
const data = parseFloat(
await browser.eval('localStorage.getItem("Next.js-hydration")')
)
Expand All @@ -81,6 +82,7 @@ function runTest() {
)
let cls = await browser.eval('localStorage.getItem("CLS")')
expect(h1Text).toMatch(/Foo!/)
expect(pText).toMatch('buffered metrics: 0')
expect(data).not.toBeNaN()
expect(data).toBeGreaterThan(0)
expect(firstByte).not.toBeNaN()
Expand Down