我试图了解在服务人员提供内容时铬的实际作用。但是我看到一个非常奇怪的行为。
这里是测试用例:我创建了一个非常简单的应用程序,它公开了一个链接。当用户单击链接时,它将获取2MB的javascript文件(该文件先前已在Service Worker安装阶段存储在缓存中)。服务工作人员拦截提取操作,并使用缓存来提供文件。
我在主线程中添加了一个console.log来测量获取响应所需的时间:
function fetchScript() {
const t = performance.now();
fetch("portal.js")
.then((response) => console.log("took", performance.now() - t, response.text()));
}
我比较了devtools中的“网络”选项卡:
如果我们在“网络”选项卡中打开一个请求的详细信息,我们将看到时间花在Content Download
上,而official spec中的时间指的是The browser is receiving the response
。
Content Download
操作如何比实际提取时间更长?我期望控制台日志显示的时间比“网络”选项卡中的时间更长(或至少相等)。有人真的知道Content Download
期间发生了什么吗?
答案 0 :(得分:1)
因此,看来Content Download
阶段是指读取响应正文的时间(从可用标头到读取正文的时间)
function fetchScript() {
const t = performance.now();
fetch("portal.js")
.then((response) => console.log("took", performance.now() - t,
response.text()));
}
在头可用时解析获取,而不是在读取正文时解析。因此,记录的时间可以小于网络时间的Content Download
时间。要将Content Download
时间包括在控制台记录的时间中,我们需要读取响应:
function fetchScript() {
const t = performance.now();
fetch("portal.js")
.then(response => response.text())
.then(response => console.log("took", performance.now() - t));
}
(但是,Content Download
时间是浏览器的度量,它没有考虑事件循环,更具体地说,没有考虑事件循环处理读取响应后排队的微任务所花费的时间: response => console.log("took", performance.now() - t)
。因此,我们将无法测量“网络”标签和console.log之间的相同时间