在前端监控API中使用了Performace接口,但目前大部分文章只列出其自身的属性或方法。实战中用到的场景比较少,自己也走了一些弯路。现在把这些记录下来,以便我们一起讨论。先说下使用场景吧。页面加载完成后记录后台界面,页面跳转前也记录后台界面。在录制一个接口之前,需要区分该接口是否需要录制,不会重复录制。关于如何标记接口数据是否被记录,我试过四种方法,在记录的接口上加上outdate字段,标记为true。使用performace.mark方法进行标记,每次只记录最后一次标记后的界面。使用performance.mark的方式进行标记,但是比较的是responseEnd字段大于标记的startTime字段(为了比较,后面再看代码)。使用全局变量记录发送的接口数,每次根据变量截取performance.getEntries()返回的数组。更新变量1和2的值被消除了。3因为时间关系只处理idea阶段,后测可行。目前使用4个。下面就说说方法遇到的问题。1.Performance是只读的,虽然现在大多数浏览器都支持在PerformanceEntry中添加字段,但是有些浏览器不允许,比如IE11,chrome的某些版本,MDN目前标记为只读constentries=performance.getEntries();//下面的方法只是过滤发送接口后,需要过滤掉发送埋点请求的接口constfreshEntries=entries.filter(item=>!item.outdate&&item.entryType==="resource"&&item.initiatorType==="xmlhttprequest");entries.forEach(item=>{item.outdate=true;});返回新鲜条目||[];2.标记发送请求但未返回数据的接口会出现在接口返回后才标记。没有按预期出现在标记之后,因为PerformanceEntry是按startTime排序的constentries=performance.getEntries();entries.reverse();if(entries[0].entryType==='mark'&&entries[0].name==='MARKNAME'){返回[];}//这段时间为了防止接口请求,先标记数据再处理数据performance.mark('MARKNAME');constendIndex=entries.findIndex(i=>i.entryType==='mark'&&i.name==='MARKNAME');constfreshEntries=entries.slice(0,endIndex).filter(item=>item.entryType==='resource'&&item.initiatorType==='xmlhttprequest');返回新鲜条目||[];3.标记后,比较标记时间和界面返回时间,直接上传代码!更简单直接的constentries=performance.getEntries();constmarkList=performance.getEntriesByName('MARKNAME');markList.reverse();constmarkTime=markList.length?标记列表[0].开始时间:0;//防止在此期间,如果有接口请求,先标记,再处理数据performance.mark('MARKNAME');constfreshEntries=entries.filter(item=>item.entryType==="资源"&&item.ininitiatorType==="xmlhttprequest"&&item.responseEnd>markTime//比较接口的返回时间和上次标记的时间);返回新鲜条目||[];项目使用typeScript,包报Property'responseEnd'doesnotexistontype'PerformanceEntry',我对ts语法不是很熟悉,先放弃了。4.记录已发送接口数的方法很简单。之所以一开始没有用,是因为不想创建全局变量,还要拦截数组,给字段赋值后,由于时间问题只能做。//初始化时,alreadySendApiNum设置为0constentries=performance.getEntries();constfreshEntries=entries.filter(item=>item.entryType==='resource'&&item.initiatorType==='xmlhttprequest');返回新鲜条目||[];freshEntries.slice(alreadySendApiNum)...//记录接口数据alreadySendApiNum=freshEntries.length;本人对性能了解有限,希望对屏幕前的你有所帮助。如有侵权请告知
