干货:如何实现一个简单的前端性能和fetch请求十分钟实时监控?最近学习了系统中的分布式微服务架构,最后的技术冲刺。今天的文章开始是因为一年前一个朋友的问题:如何实时监控fetch请求,因为他想给谷歌浏览器写一个插件来实时监控nativefetch请求。众所周知,fetch的源码是对原生ajax的封装。网上有个办法,改写fetch,然后实现效果。我坚决拒绝这种操作,于是对前端性能监控做了全面的研究,终于找到了办法。首先,你需要知道Performance的API我们先从最简单的说起。我们查看performance.timing并获得以下数据。我们将上面的数据对象传入组装数据的函数中:下面有详细的注释,直接看代码copy使用,当然SPA页面的监控可能需要自定义微调,就不说了在这里详细介绍。//处理数据函数handleData(performance){letnavigationStart=performance.navigationStart||performance.fetchStartletperformanceData={}if(performance){//重定向时间performanceData.redirectTime=performance.redirectEnd-performance.redirectStart//缓存时间performanceData.cacheTime=performance.domainLookupStart-performance.fetchStart//dns查询时间performanceData.dnsTime=performance.domainLookupEnd-performance.domainLookupStart//tcp握手时间performanceData.TcpTime=performance.connectEnd-performance.connectStart//ajax请求时间performanceData.ajaxTime=performance.responseEnd-performance.requestStart//开始解析dom的时候,此时document.readyState变成loadingperformanceData.domLoadingTime=performance.domLoading?performance.domLoading-navigationStart:null//dom解析完成时间,此时document。readyState变为交互式performanceData.domInteractiveTime=performance.domInteractive-navigamotionStart//dom解析完成,资源加载完成,脚本完成performance.loadEventEnd-navigationStart:null}returnperformanceData}数据组装后,触发window.onload事件时发送:window.onload=function(){lettiming=window.performance.timing;让performanceData=handleData(timing)performanceData.timestamp=Date.now()performanceData.url=location.hrefperformanceData.from='window.performance'performanceData=Object.assign({},performanceData,getPaintTime())send(performanceData)}最后上报并发送组装好的数据:那么问题来了,如何监控fetchrequests呢?那么一定要有一个事件,而且是观察者模式。这里使用了APIMDN对PerformanceObserver的介绍:PerformanceObserver用于监控性能测量事件,当浏览器的性能时间线中记录了新的性能条目时会收到??通知。Observer.observe()指定要监视的条目类型的集合。当性能入口被记录并且是指定的entryTypes之一时,将调用性能观察者对象的回调函数。当我们构造和调用PerformanceObserver时,我们传入一个函数perf_observer,指定entryTypes为resource,当我们发送fetch请求时,perf_observer函数会被调用functionperf_observer(list,observer){console.log(list,observer,'resource',performance.getEntries())}perf_observerfunction:functionperf_observer(list,observer){console.log(list,observer,'resource',performance.getEntries())}发送fetch请求时,看打印结果:以这种方式,每次发送一个fetch请求,然后我们打印performance.getEntries(),就可以看到fetch请求了。当然,你可以在这里写一个diff算法,把结果缓存一份,给每个请求一个唯一的key值。每次fetch请求触发perf_observer函数,只有latest和previous没有值,可以上报。虽然不是什么高深的知识点,但是还是蛮实用的。如果觉得不错,可以点开阅读。懂源码的人自己看。看不懂,写了也不会看。写文章很尴尬。长按二维码关注我们。有趣的内容等你的个人微信:CALASFxiaotan
