前端监控五性能监控和最佳实践

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()

记录重要函数执行时间

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

和 JavaScript
中其他可用的时间类函数(比如Date.now)不同的是,window.performance.now()返回的时间戳没有被限制在一毫秒的精确度内,相反,它们以浮点数的形式表示时间,精度最高可达微秒级。

另外一个不同点是,window.performance.now()是以一个恒定的速率慢慢增加的,它不会受到系统时间的影响(系统时钟可能会被手动调整或被
NTP 等软件篡改)。另外,performance.timing.navigationStart + performance.now()
约等于 Date.now()。

页面停留时间

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首屏时间

首次内容绘制 (FCP) 指标测量页面从开始加载到页面内容的任何部分在屏幕上完成渲染的时间。
来自 google.com 的 FCP 时间轴
在上方的加载时间轴中,FCP 发生在第二帧,因为那是首批文本和图像元素在屏幕上完成渲染的时间点。

您会注意到,虽然部分内容已完成渲染,但并非所有内容都已经完成渲染。

计算方法

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

PerformanceTiming 接口是为保持向后兼容性而保留的传统接口,并且提供了在加载和使用当前页面期间发生的各种事件的性能计时信息。

因为 Navigation Timing 规范已被弃用,此特性不再有望成为标准。请使用 PerformanceNavigationTiming 接口代替。

performance.getEntriesByType("navigation")[0]

新一代性能指标 Web Vitals

什么是WebVitals ? Web Vitals,即 Google 给的定义是一个良好网站的基本指标(Essential
metrics for a healthy site) Performance已经包含了很多指标,为什么 Google
还要再去定义一个新的指标集

这是因为,在过去要去衡量一个高质量网站,需要的指标太多,且有些指标计算很复杂,所以,Google 推出 Web Vitals
就是为了简化这个过程,用户仅仅需要关注 Web Vitals 即可。

扫描二维码关注公众号,回复: 17002002 查看本文章

在 Web Vitals 中,Core Web Vitals 是最核心的,它包含以下三个指标:

LCP (Largest Contentful Paint)

最大内容绘制时间,用来衡量加载体验,谷歌要求LCP最好在页面首次开始加载后的2.5秒内发生;
长久以来,对于网页开发者来说,测量网页主要内容的加载速度和内容对用户的显示速度一直是一个挑战。

诸如load(加载)或DOMContentLoaded(DOM内容加载完毕)这样的旧有指标并不是很好,因为这些指标不一定与用户在屏幕上看到的内容相对应。而像First Contentful Paint
首次内容绘制 (FCP)这类以用户为中心的较新性能指标只会捕获加载体验最开始的部分。如果某个页面显示的是一段启动画面或加载指示,那么这些时刻与用户的关联性并不大。

https://web.dev/lcp/

FID (First Input Delay)

首次输入延迟时间,用于衡量页面交互性,谷歌要求页面的FID最好小于100毫秒;

CLS (Cumulative Layout Shift)

累计布局位移,用于衡量视觉稳定性,谷歌要求页面的CLS最好保持小于0.1。

页面内容的意外移动通常是由于异步加载资源,或者动态添加 DOM
元素到页面现有内容的上方。罪魁祸首可能是未知尺寸的图像或视频、实际渲染后比后备字体更大或更小的字体,或者是动态调整自身大小的第三方广告或小组件。

react中新增的reportWebVitals.js文件

create-react-app脚手架创建的项目(版本可以通过npm list -g查看),已经新增了reportWebVitals.js文件,内容如下:

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;

通过把index.js文件的最后一行改为:

reportWebVitals(console.warn);

控制台会打印出来
FCP
https://create-react-app.dev/docs/running-tests/

web-vitals库最佳实践

Google 提供了的一个小而美 npm 包: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);

猜你喜欢

转载自blog.csdn.net/uotail/article/details/131864592