首先,在开始监控前端性能之前,需要了解一个全局对象 —- Performance
Performance
Performance 接口可以获取到当前页面中与性能相关的信息。
它是 High Resolution Time API 的一部分,同时也融合了 Performance Timeline API、Navigation Timing API、 User Timing API 和 Resource Timing API。可以通过调用只读属性 Window.performance 来获得。
属性
- Performance.navigation 对象提供了在指定的时间段里发生的操作相关信息,包括页面是加载还是刷新、发生了多少次重定向等等。
- Performance.timing 对象包含延迟相关的性能信息。
- performance.memory 其是 Chrome 添加的一个非标准扩展,这个属性提供了一个可以获取到基本内存使用情况的对象。
- Performance.timeOrigin 返回性能测量开始时的时间的高精度时间戳。
- Performance.onresourcetimingbufferfull 一个回调的 EventTarget,当触发 resourcetimingbufferfull 事件的时候会被调用。
方法
Performance 接口没有继承任何方法。
Performance.clearMarks()
将给定的 mark 从浏览器的性能输入缓冲区中移除。
Performance.clearMeasures()
将给定的 measure 从浏览器的性能输入缓冲区中。
Performance.clearResourceTimings()
从浏览器的性能数据缓冲区中移除所有 entryType 是 “resource” 的 performance entries。
Performance.getEntries()
基于给定的 filter 返回一个 PerformanceEntry 对象的列表。
Performance.getEntriesByName()
基于给定的 name 和 entry type 返回一个 PerformanceEntry 对象的列表。
Performance.getEntriesByType()
基于给定的 entry type 返回一个 PerformanceEntry 对象的列表。
Performance.mark()
根据给出 name 值,在浏览器的性能输入缓冲区中创建一个相关的timestamp。
Performance.measure()
在浏览器的指定 start mark 和 end mark 间的性能输入缓冲区中创建一个指定的 timestamp。
Performance.now()
返回一个表示从性能测量时刻开始经过的毫秒数 DOMHighResTimeStamp。
Performance.setResourceTimingBufferSize()
将浏览器的资源 timing 缓冲区的大小设置为 “resource” type performance entry 对象的指定数量。
Performance.toJSON() Not available to workers
其是一个 JSON 格式转化器,返回 Performance 对象的 JSON 对象。
监控页面性能
监控页面性能 实质上就是计算页面响应的时间,也就是通过 Performance中的timing属性 算时间差。
从输入url到用户可以使用页面的全过程时间统计,会返回一个PerformanceTiming对象,单位均为毫秒(ms)。

const getPerformanceTiming = () => {let performance = window.performance;if (!performance) {// 当前浏览器不支持console.log('你的浏览器不支持 performance 接口');return;}let t = performance.timing;let times = {};//【重要】页面加载完成的时间times.onload = t.loadEventEnd - t.navigationStart;//【重要】解析DOM树结构的时间,包括内嵌资源times.domResolved = t.domComplete - t.domLoading;//【重要】dom准备开始解析,从最开始到准备开始解析DOM的时间times.domReadyResolve = t.domLoading - t.navigationStart;//【重要】白屏时间,读取页面第一个字节的时间times.firstPaint = t.responseStart - t.navigationStart;//【重要】内容加载完成的时间times.request = t.responseEnd - t.requestStart;//【重要】time to interactivetimes.tti = t.domInteractive - t.requestStart;return times;}
下图是谷歌对前端页面展示时间节点的规范:

FP:表示当第一个元素被渲染的时候,这为首次节点,我们可以默认为是第一个字节被读取的时候,它就开始了,因为浏览器是一边读取一边渲染的。
FCP:表示第一个内容节点被渲染的时候,可能是某个文本,导航栏,svg图片等。
FMP:表示第一个有意义的展示,也就是最大程度的页面变化时,会算这个节点。
TTI:表示页面从用户角度变为交互所需的时间,而不一定是当页面正式完成加载时。页面的初始JS被加载和主线程闲置的点(没有长任务)。
最后,贴一个小爝的github的前端监控项目。
监控单个资源的加载状态
Performance.getEntries()
基于给定的 filter 返回一个 PerformanceEntry 对象的列表。
Performance.getEntriesByName()
基于给定的 name 和 entry type 返回一个 PerformanceEntry 对象的列表。
Performance.getEntriesByType()
基于给定的 entry type 返回一个 PerformanceEntry 对象的列表。
可通过Performance.getEntries() 相关方法获取资源的相关信息。
监控http请求发送状况
在目前的浏览器当中,发送http请求的方式有两种,通过XHRHttpRequest 和 fetch方法。
而我们需要捕获http请求的信息,一般是在发送时或者返回时做面向切面编程处理(AOP)。
如axios中的拦截器(interceptors)就是在请求时和返回时加入切面函数得到相关信息并进行操作。
// Add a request interceptor
axios.interceptors.request.use(function (config) {
// Do something before request is sent
return config;
}, function (error) {
// Do something with request error
return Promise.reject(error);
});
// Add a response interceptor
axios.interceptors.response.use(function (response) {
// Do something with response data
return response;
}, function (error) {
// Do something with response error
return Promise.reject(error);
});
XMLHttpRequest
在原生ajax当中 也可以进行类似操作,重写xhr的原型方法
XMLHttpRequest can be used to retrieve any type of data, not just XML, and it supports protocols other than HTTP (including file and ftp).
const xhr = window.XMLHttpRequest
const _open = xhr.prototype.open
const _send = xhr.prototype.send
const _error = xhr.prototype.error
xhr.prototype.open = function (method, url, ...) {
//编辑
return _open.apply(this, args)
}
xhr.prototype.send = function (args, ...) {
//编辑
return _send.apply(this, args)
}
Fetch
想要监控fetch请求 可以在window.fetch的上一层封装一层如axios一样的拦截器
下面是MDN中的一个例子
function postData(url, data) {
// Default options are marked with *
return fetch(url, {
body: JSON.stringify(data), // must match 'Content-Type' header
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
credentials: 'same-origin', // include, same-origin, *omit
headers: {
'user-agent': 'Mozilla/4.0 MDN Example',
'content-type': 'application/json'
},
method: 'POST', // *GET, POST, PUT, DELETE, etc.
mode: 'cors', // no-cors, cors, *same-origin
redirect: 'follow', // manual, *follow, error
referrer: 'no-referrer', // *client, no-referrer
})
.then(response => {
// 获取到response 对象进行操作 然后返回
return response.json()
}) // parses response to JSON
}
postData('http://example.com/answer', {answer: 42})
.then(data => console.log(data)) // JSON from `response.json()` call
.catch(error => console.error(error))
捕获页面的错误
window.onerror函数会在页面发生js错误时被调用。
window.onerror = function(message, source, lineno, colno, error) { ... }
我们可以看到函数正常是可以收集到错误字符串信息、发生错误的js文件,错误所在的行数、列数、和Error对象(里面会有调用堆栈信息等)。
然后把对应的调用堆栈的信息发送给服务端,配合sourcemap文件就能找到对应源码了。
