Skip to main content

衡量性能

默认情况下,Create React App 包含一个性能中继器,允许你使用不同的指标来衡量和分析应用的性能。

¥By default, Create React App includes a performance relayer that allows you to measure and analyze the performance of your application using different metrics.

要测量任何支持的指标,你只需要将一个函数传递到 index.js 中的 reportWebVitals 函数中:

¥To measure any of the supported metrics, you only need to pass a function into the reportWebVitals function in index.js:

reportWebVitals(console.log);

当任何指标的最终值在页面上完成计算时,将触发此函数。你可以使用它将任何结果记录到控制台或发送到特定端点。

¥This function is fired when the final values for any of the metrics have finished calculating on the page. You can use it to log any of the results to the console or send to a particular endpoint.

Web Vitals

Web Vitals 是一组有用的指标,旨在捕捉网页的用户体验。在 Create React App 中,第三方库用于衡量这些指标 (web-vitals)。

¥Web Vitals are a set of useful metrics that aim to capture the user experience of a web page. In Create React App, a third-party library is used to measure these metrics (web-vitals).

要了解有关计算度量值时返回给函数的对象的更多信息,请参阅 documentation浏览器支持 部分还解释了支持哪些浏览器。

¥To understand more about the object returned to the function when a metric value is calculated, refer to the documentation. The Browser Support section also explains which browsers are supported.

将结果发送到分析

¥Sending results to analytics

使用 reportWebVitals 函数,你可以将任何结果发送到分析端点以衡量和跟踪你网站上的真实用户性能。例如:

¥With the reportWebVitals function, you can send any of results to an analytics endpoint to measure and track real user performance on your site. For example:

function sendToAnalytics(metric) {
const body = JSON.stringify(metric);
const url = 'https://example.com/analytics';

// Use `navigator.sendBeacon()` if available, falling back to `fetch()`
if (navigator.sendBeacon) {
navigator.sendBeacon(url, body);
} else {
fetch(url, { body, method: 'POST', keepalive: true });
}
}

reportWebVitals(sendToAnalytics);

注意:如果你使用 Google Analytics,请使用 id 值更轻松地手动构建指标分布(计算百分位数等)。

¥Note: If you use Google Analytics, use the id value to make it easier to construct metric distributions manually (to calculate percentiles, etc…).

function sendToAnalytics({ id, name, value }) {
ga('send', 'event', {
eventCategory: 'Web Vitals',
eventAction: name,
eventValue: Math.round(name === 'CLS' ? value * 1000 : value), // values must be integers
eventLabel: id, // id unique to current page load
nonInteraction: true, // avoids affecting bounce rate
});
}

reportWebVitals(sendToAnalytics);

阅读有关将结果发送到 Google Analytics 此处 的更多信息。

¥Read more about sending results to Google Analytics here.