如何访问网页中每个资源的性能对象?

时间:2013-07-17 05:36:54

标签: javascript browser web pageload

我可以在 Chrome开发者工具中查看网页中所有资源的加载时间,从服务器获取特定资源所需的时间以及其他信息。

我想使用JavaScript捕获这些统计信息。怎么可能?

有window.performance对象可用,但仅适用于请求的页面,不适用于页面资源。 有没有办法访问所有页面资源的性能对象。

3 个答案:

答案 0 :(得分:4)

最新版本的Chrome还有一个错误 - 29.0.1547.76 m 当您提出xmlhttprequest时,让我们说在下载图像时,您可以看到资源是在网络选项卡中以状态代码200 OK下载的,但是performance.getEntries()或performance.getEntriesByName(resourceUrl)没有列出资源条目。页面加载完成后,您在控制台中评估performance.getEntriesByName(resourceUrl),它会正确列出。那么,在填充性能条目中的资源条目时,chrome存在延迟? 在IE10中,这完全正常。

答案 1 :(得分:3)

您应该可以使用window.performance.getEntries()获取特定于资源的统计信息:

var resource = window.performance.getEntries()[0];

console.log(resource.entryType);  // "resource"
console.log(resource.duration);   // 39.00000000430737
console.log(resource.startTime);  // 218.0000000007567

以上链接中的示例:

  

enter image description here

答案 2 :(得分:1)

window.performance.getEntries() 可能不会返回所有资源。缓冲后,一些记录消失了 需要在它发生之前检查它

头部代码部分

var storedEntries = [];
var updateStoredEntries = p => {
  storedEntries.concat(
    p.getEntries().filter(rec => /yourRegExp/.test(rec.name))
  )
};
performance.addEventListener('resourcetimingbufferfull', e => {
  updateStoredEntries(e.target)
});

... 后来的部分

updateStoredEntries(performance)