Performance
深入浅出前端监控
Performance 接口可以获取到当前页面中与性能相关的信息。它是 High Resolution Time API 的一部分,同时也融合了 Performance Timeline API、Navigation Timing API、 User Timing API 和 Resource Timing API。
PerformanceEntry 对象代表了performance时间列表中单个 metric数据。

performance.getEntries();

image.png

FP

First Paint 首次绘制,是时间线上的第一个时间点,它代表网页的第一个像素渲染到屏幕上所用的时间,也就是屏幕上首次发生视觉变化的时间。

  1. function getFPTime(){
  2. const timings = performance.getEntriesByType('paint')[0];
  3. return timings ? Math.round(timings.startTime) : null
  4. }

FCP

Firtst Contentful Paint 首次内容绘制 它代表浏览器第一次向屏幕绘制内容。
注意:只有首次绘制 文本 图片(包含背景图) 非白色的canvas svg时才算座FCP。
通过performance.getEntriesByType(‘paint’),取第二个pain的时间,或者通过Mutation Observer观察到首次节点变动的时间

  1. const domEntries = []
  2. const observer = new MutationObserver((mutationsList)=>{
  3. for(var mutation of mutationsList) {
  4. if (mutation.type == 'childList') {
  5. console.log('A child node has been added or removed.');
  6. }
  7. if (mutation.type == 'addedNodes') {
  8. //TODO新增了节点,做处理,计算此时的可见性/位置/出现时间等信息,然后 push 进数组
  9. ...
  10. domEntries.push(mutation)
  11. }
  12. }
  13. });
  14. function getFPTime(){
  15. const timings = performance.getEntriesByType('paint');
  16. if(timings.length > 1)return timings[1]
  17. return timings ? Math.round(timings.startTime) : null
  18. //伪代码,算 DOM 变化时的最小那个时间,即节点首次变动的时间
  19. return Math.round(domEntries.length ? Math.min(...domEntries.map(entry => entry.time)) : 0);
  20. }

FMP

First Meaningful Paint 首次有意义的绘制,是页面主要内容出现在屏幕上的时间,这是用户感知加载体验的指标。
目前尚无标准的定义,因为很难以通用方式确定各种类型页面的关键内容。
fmp-tti
tti-polyfill

FID

First Input Delay 首次输入延迟,是测量用户首次与您的站点交互时的时间(即当他们单击链接/点击按钮/使用自定义的JavaScript驱动控件时)到浏览器实际能够回应这种互动的时间。

  1. 通过performanceObserver(目前支持性为88.78%)观察类型为first-input的entry,获得其startTime/duration等数即可
  2. 初始化时为特定事件类型(click/touch/keydown)绑定通用统计逻辑事件,开始调用时从event.timeStamp取开始处理的时间(这个时间就是首次输入延迟时间),在事件处理中注册requestIdleCallback事件回调onIdleCallback,当onIdleCallback被执行时,当前时间减开始的event.timeStamp即为duration时间 ``` // 方式一 function getFIDTime(){ const timings = performance.getEntriesByType(‘first-input’)[0]; return timings ? timings : null } // 方式二,以下代码仅代表思路

[‘click’,’touch’,’keydown’].forEach(eventType => { window.addEventListener(eventType, eventHandle); });

function eventHandle(e) { const eventTime = e.timeStamp; window.requestIdleCallback(onIdleCallback.bind(this, eventTime, e)); }

function onIdleCallback(eventTime, e) { const now = window.performance.now(); const duration = now - eventTime;

  1. return {
  2. duration: Math.round(duration),
  3. timestamp: Math.round(eventTime)
  4. }
  5. ['click','touch','keydown'].forEach(eventType => {
  6. window.removeEventListener(eventType, eventHandle);
  7. });

}

  1. <a name="wWGyK"></a>
  2. ### TTI
  3. Time To Interactive 可交互时间

import ttiPolyfill from ‘tti-polyfill’;

ttiPolyfill.getFirstConsistentlyInteractive().then((tti) => { ga(‘send’, ‘event’, { eventCategory:’Performance Metrics’, eventAction:’TTI’, eventValue: tti, nonInteraction: true, }); });

  1. 在页面加载的一定时间内(如前50s内),以(domContentLoadedEventStart-navigationStart)+5为起始点,循环寻找,找到一个5s的窗口,其中网络请求不超过2个且没有长任务(>50ms),再找到该5秒窗口之前的最后一个长任务,该长任务结束的时间点就是可稳定交互时间。其中长任务可自定义时间或通performance.getEntriesByType('long-task')获取

// 以下代码仅代表思路 const basicTime = 5000;

function getTTITime(startTime,longTaskEntries, resourceEntries,domContentLoadedTime) {

let busyNetworkInWindow = []; let tti = startTime;

while (startTime + basicTime <= 50000) { //从前50s 中去找 tti = startTime; longTasksInWindow = longTaskEntries.filter(task => { return task.startTime < startTime + basicTime && task.startTime + task.duration > startTime; }); if (longTasksInWindow.length) { const lastLongTask = longTasksInWindow[longTasksInWindow.length - 1]; startTime = lastLongTask.startTime + lastLongTask.duration; continue; } busyNetworkInWindow = resourceEntries.filter(request => { return !(request.startTime >= startTime + basicTime || request.startTime + request.duration <= startTime); }); if (busyNetworkInWindow.length > 2) { const firstRequest = busyNetworkInWindow[0]; startTime = firstRequest.startTime + firstRequest.duration; continue; } return Math.max(tti, domContentLoadedTime); } return Math.max(tti, domContentLoadedTime); } ```

FCI

First CPU Idle,翻译为首次CPU空闲时间代表着一个网页已经满足了最小程度的与用户发生交互行为的时刻。当我们打开一个网页,我们并不需要等到一个网页完全加载好了,每一个元素都已经完成了渲染,然后再去与网页进行交互行为。网页满足了我们基本的交互的时间点是衡量网页性能的一个重要指标
###

FPS

Frames Per Second,翻译为每秒帧率,表示的是每秒钟画面更新次数,当今大多数设备的屏幕刷新率都是60次/秒。

利用requestAnimationFrame,循环调用,当now大于lastTime+1S时,计算FPS。若小于某个阀值则可以认为当前帧率较差,若连续小于多个阀值,则停止统计,当前页面处于卡顿状态,进入卡顿处理逻辑
链接2324
web动画帧率FPS计算

设备信息

从window.navigator.userAgent中可以获取用户设备信息
image.png
从window.navigator.connection中可以获取设备网络信息

image.png
从window.devicePixelRatio可以获取设备像素比。

上报策略

pv/uv

监听各种页面切换的情况;SPA页面,可以监听hashChange

性能数据/设备信息/网络状况

  • 在页面离开前上报,beforeUnload/visibilitychange/pagehide…+sendBeancon/Ajax
  • img 标签+切片+压缩

image.png