这是我参与「第四届青训营 」笔记创作活动的第3天
前言
这是我在本次大项目中负责的部分,再次感受到了浏览器是一个多么复杂精妙的一个巨大工程。
基础内容
这是精度更高,功能更强大,层次更分明的 Level 2规范
可以看出其中展示了非常完善丰富的性能指标api
FP & FCP
对于基础的FP和FCP内容,可以通过以下js内置对象在浏览器中获取
new PerformanceObserver((entryList) => {
console.log(entryList.getEntries());
console.log(
"FP 白屏时间",
entryList.getEntriesByName("first-paint")[0].startTime
);
console.log(
"FCP 灰屏时间",
entryList.getEntriesByName("first-contentful-paint")[0].startTime
);
}).observe({ type: "paint", buffered: true });
其中.observe中buffered属性的为是否利用浏览器缓存
- 首先理解第一点,浏览器初始化完后,performance所有的指标,即使我们不使用PerformanceObserver去取各类参数,浏览器都会自己去把所有的数据获取下来并缓存到内存中;
- 第二点,buffered 这个参数的作用是:既然有了缓存,就用这个参数来决定,调用PerformanceObserver接口时,是否要将在函数初始化之前发生的性能缓冲数据拿进来执行;好比你现在F12打开控制台,分别用 true 和 false 去取一下FP的指标,你会发现只有true的有值出来,为什么呢?因为true拿了之前就缓冲好的FP,false不考虑已缓存的,只有新产生的才会触发;
DOMReady & DNSDuration
这部分在浏览器提供的api中与FP,FCP不在同一个对象中
new PerformanceObserver((entryList) => {
const {
domContentLoadedEventEnd,
fetchStart,
domainLookupEnd,
domainLookupStart,
} = entryList.getEntries()[0];
console.log(entryList.getEntries()[0]);
console.log("fetchSatrt", fetchStart);
console.log("domContentLoadedEventEnd", domContentLoadedEventEnd);
console.log(
"DomReady HTML加载完成时间",
domContentLoadedEventEnd - fetchStart
);
console.log("domainLookupStart DNS域名解析开始", domainLookupStart);
console.log("domainLookupEnd DNS域名解析结束", domainLookupEnd);
console.log("DNS查询时间", domainLookupEnd - domainLookupStart);
}).observe({ entryTypes: ["navigation"] });
此处则是利用.observe筛选entryTypes,从中解构赋值想要的参数,计算得出DOMReady和DNSDuration的时间