Front-end monitoring five performance monitoring and best practices

performance

https://developer.mozilla.org/zh-CN/docs/Web/API/PerformanceTiming
https://developer.mozilla.org/zh-CN/docs/Web/API/Performance/getEntriesByType
https://developer.mozilla.org/zh-CN/docs/Web/API/Performance/now

performance.now()

Record important function execution time

const t0 = window.performance.now();
doSomething();
const t1 = window.performance.now();
console.log("doSomething 函数执行了" + (t1 - t0) + "毫秒。")


Unlike other time functions available in JavaScript (such as Date.now), the timestamps returned by window.performance.now() are not limited to one millisecond accuracy. Instead, they are represented as floating point numbers . Time, the accuracy can reach up to microsecond level.

Another difference is that window.performance.now() slowly increases at a constant rate and will not be affected by the system time (the system clock may be manually adjusted or tampered with by
software such as NTP). In addition, performance.timing.navigationStart + performance.now()
is approximately equal to Date.now().

Time on page

let pageShowTime = 0
let timeOnPage = 0
window.addEventListener('pageshow', () => {
    
    
    pageShowTime = performance.now()
     // 页面性能指标上报
    reportWebVitals((data) => {
    
    
      this.performanceReport({
    
     data })
    })
    // 执行 onPageShow
    this.onPageShow();
  })
 
window.addEventListener('pagehide', () => {
    
    
  // 记录用户在页面停留时间
 timeOnPage = performance.now() - pageShowTime

FCP first screen time

The First Content Paint (FCP) metric measures the time from when a page starts loading until any part of the page content has finished rendering on the screen.
FCP timeline from google.com
In the loading timeline above, FCP occurs on the second frame because that's when the first text and image elements finish rendering on the screen.

You'll notice that while some content has finished rendering, not everything has finished rendering.

Calculation method

new PerformanceObserver((entryList) => {
    
    
  for (const entry of entryList.getEntriesByName('first-contentful-paint')) {
    
    
    console.log('FCP candidate:', entry.startTime, entry);
  }
}).observe({
    
    type: 'paint', buffered: true});

https://developer.mozilla.org/zh-CN/docs/Web/API/PerformanceObserver

window.performance.timing

The PerformanceTiming interface is a legacy interface retained for backward compatibility and provides performance timing information for various events that occur during the loading and use of the current page.

Because the Navigation Timing specification has been deprecated, this feature is no longer expected to become a standard. Please use the PerformanceNavigationTiming interface instead.

performance.getEntriesByType("navigation")[0]

A new generation of performance indicators, Web Vitals

What are WebVitals? Web Vitals, which is the definition given by Google, is the basic metrics for a healthy site (Essential
metrics for a healthy site). Performance already contains many metrics. Why does Google
need to define a new set of metrics ?

This is because in the past, too many indicators were needed to measure a high-quality website, and the calculation of some indicators was very complicated. Therefore, Google launched Web Vitals
to simplify this process. Users only need to pay attention to Web Vitals.

Among Web Vitals, Core Web Vitals is the core, which includes the following three indicators:

LCP (Largest Contentful Paint)

Maximum content drawing time is used to measure the loading experience. Google requires that LCP should preferably occur within 2.5 seconds after the page first starts loading. For a long time,
for web developers, measuring the loading speed of the main content of the web page and the impact of the content on the user Display speed has always been a challenge.

Older metrics like load or DOMContentLoaded (DOM content loaded) are not very good because these metrics do not necessarily correspond to what the user sees on the screen.
Newer user-centric performance metrics like First Contentful Paint (FCP) only capture the very beginning of the loading experience. If a page displays a splash screen or loading instructions, those moments are less relevant to the user.

https://web.dev/lcp/

FID (First Input Delay)

First input delay time is used to measure page interactivity. Google requires that the FID of the page should be less than 100 milliseconds;

CLS (Cumulative Layout Shift)

Cumulative layout displacement is used to measure visual stability. Google requires that the CLS of the page should preferably be kept less than 0.1.

Unexpected movement of page content is usually caused by loading resources asynchronously, or dynamically adding DOM
elements on top of the existing content of the page. The culprit could be an image or video of unknown dimensions, a font that actually renders larger or smaller than the fallback font, or a third-party ad or widget that dynamically resizes itself.

The reportWebVitals.js file newly added in react

The project created by create-react-app scaffolding (the version can be viewed through npm list -g) has a new reportWebVitals.js file with the following content:

const reportWebVitals = onPerfEntry => {
    
    
  if (onPerfEntry && onPerfEntry instanceof Function) {
    
    
    import('web-vitals').then(({
     
      getCLS, getFID, getFCP, getLCP, getTTFB }) => {
    
    
      getCLS(onPerfEntry);
      getFID(onPerfEntry);
      getFCP(onPerfEntry);
      getLCP(onPerfEntry);
      getTTFB(onPerfEntry);
    });
  }
};

export default reportWebVitals;

By changing the last line of the index.js file to:

reportWebVitals(console.warn);

The console will print out
FCP
https://create-react-app.dev/docs/running-tests/

web-vitals library best practices

Google provides a small but beautiful npm package: web-vitals,

import {
    
    onCLS, onFID, onLCP} from 'web-vitals';

function sendToAnalytics({
     
     name, value, id}) {
    
    
  const body = JSON.stringify({
    
    name, value, id});
  // 可以的话,使用 `navigator.sendBeacon()`, 回退到 `fetch()`.
  (navigator.sendBeacon && navigator.sendBeacon('/analytics', body)) ||
      fetch('/analytics', {
    
    body, method: 'POST', keepalive: true});
}
onCLS(sendToAnalytics);
onFID(sendToAnalytics);
onLCP(sendToAnalytics);

Guess you like

Origin blog.csdn.net/uotail/article/details/131864592