Resource Timing API

Resource Timing API 提供了获取和分析应用程序资源加载的详细网络计时数据的一种途径。应用可以使用一些可量化的时间度量标准,如加载特定资源的时长。这些资源可能是 XMLHttpRequest<SVG>、图片、脚本等等。

这个接口提供了使用 高精度时间戳 度量的资源加载时间轴。此时间轴包含众多网络事件的时间,如重定向开始和结束时间,开始请求资源时间,DNS查询开始和结束时间,响应开始和结束时间等等。也包含了请求到的资源的大小、请求发起者的类型

这篇文档展示了如何使用 Resource Timing 接口。获取更详细的信息或示例,请查看每个接口的文档和See also章节。

Github上有一个真实的例子,这里是它的源码 source code. 欢迎提pull request和报告bug

资源加载的各个阶段

应用可以获取到资源加载的各个阶段的时间戳,如重定向、DNS查询、TCP连接建立。这些阶段和他们的属性名在图1中列出。

 
图 1. Resource timing 属性

应用开发者可以使用这些属性值去计算某个阶段的耗时长度,用来帮助诊断性能问题。

计算资源加载各阶段的时间

接下来的这段例子展示了用 Resource timing 属性去计算以下阶段的耗时:重定向 (redirectStart 和 redirectEnd ),DNS查询(domainLookupStart 和 domainLookupEnd),TCP握手 (connectStart 和 connectEnd), 响应 (responseStart 和 responseEnd)。 这段例子也计算了从开始获取资源和请求开始(分别为fetchStart and requestStart)到响应结束 (responseEnd) 的时间.

function calculate_load_times() {
  // Check performance support
  if (performance === undefined) {
    console.log("= Calculate Load Times: performance NOT supported");
    return;
  }

  // Get a list of "resource" performance entries
  var resources = performance.getEntriesByType("resource");
  if (resources === undefined || resources.length <= 0) {
    console.log("= Calculate Load Times: there are NO `resource` performance records");
    return;
  }

  console.log("= Calculate Load Times");
  for (var i=0; i < resources.length; i++) {
    console.log("== Resource[" + i + "] - " + resources[i].name);
    // Redirect time
    var t = resources[i].redirectEnd - resources[i].redirectStart;
    console.log("... Redirect time = " + t);

    // DNS time
    t = resources[i].domainLookupEnd - resources[i].domainLookupStart;
    console.log("... DNS lookup time = " + t);

    // TCP handshake time
    t = resources[i].connectEnd - resources[i].connectStart;
    console.log("... TCP time = " + t);

    // Secure connection time
    t = (resources[i].secureConnectionStart > 0) ? (resources[i].connectEnd - resources[i].secureConnectionStart) : "0";
    console.log("... Secure connection time = " + t);

    // Response time
    t = resources[i].responseEnd - resources[i].responseStart;
    console.log("... Response time = " + t);

    // Fetch until response end
    t = (resources[i].fetchStart > 0) ? (resources[i].responseEnd - resources[i].fetchStart) : "0";
    console.log("... Fetch until response end time = " + t);

    // Request start until reponse end
    t = (resources[i].requestStart > 0) ? (resources[i].responseEnd - resources[i].requestStart) : "0";
    console.log("... Request start until response end time = " + t);

    // Start until reponse end
    t = (resources[i].startTime > 0) ? (resources[i].responseEnd - resources[i].startTime) : "0";
    console.log("... Start until response end time = " + t);
  }
}

猜你喜欢

转载自blog.csdn.net/liuhao9999/article/details/109812870