Using the Resource Timing API

翻译不完整。 请帮助我们翻译这篇文章!

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

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

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

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

资源加载的各个阶段

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

Graphic of Resource Timing timestamps
图 1. Resource timing 属性

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

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

接下来的这段例子展示了用 Resource timing 属性去计算以下阶段的耗时:重定向 (redirectStartredirectEnd ),DNS查询(domainLookupStartdomainLookupEnd),TCP握手 (connectStartconnectEnd), 响应 (responseStartresponseEnd)。 这段例子也计算了从开始获取资源和请求开始(分别为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);
  }
}

Size matters?

The size of an application's resources can affect an application's performance so getting accurate data on resource size can be important (especially for non-hosted resources). The PerformanceResourceTiming interface has three properties that can be used to obtain size data about a resource. The transferSize property returns the size (in octets) of the fetched resource including the response header fields plus the response payload body. The encodedBodySize property returns the size (in octets) received from the fetch (HTTP or cache), of the payload body, before removing any applied content-codings. decodedBodySize returns the size (in octets) received from the fetch (HTTP or cache) of the message body, after removing any applied content-codings.

The following example demonstrates using these three properties.

function display_size_data(){
  // Check for support of the PerformanceResourceTiming.*size properties and print their values
  // if supported.
  if (performance === undefined) {
    console.log("= Display Size Data: performance NOT supported");
    return;
  }

  var list = performance.getEntriesByType("resource");
  if (list === undefined) {
    console.log("= Display Size Data: performance.getEntriesByType() is  NOT supported");
    return;
  }

  // For each "resource", display its *Size property values
  console.log("= Display Size Data");
  for (var i=0; i < list.length; i++) {
    console.log("== Resource[" + i + "] - " + list[i].name);
    if ("decodedBodySize" in list[i])
      console.log("... decodedBodySize[" + i + "] = " + list[i].decodedBodySize);
    else
      console.log("... decodedBodySize[" + i + "] = NOT supported");

    if ("encodedBodySize" in list[i])
      console.log("... encodedBodySize[" + i + "] = " + list[i].encodedBodySize);
    else
      console.log("... encodedBodySize[" + i + "] = NOT supported");

    if ("transferSize" in list[i])
      console.log("... transferSize[" + i + "] = " + list[i].transferSize);
    else
      console.log("... transferSize[" + i + "] = NOT supported");
  }
}

Managing the resource buffer

Although the browser is required to support at least 150 resource timing performance entries in its resource timing buffer, some applications may use more resources than that limit. To help the developer manage the buffer size, Resource Timing defines two methods that extend the Performance interface. The clearResourceTimings() method removes all "resource" type performance entries from the browser's resource performance entry buffer. The setResourceTimingBufferSize() method sets the resource performance entry buffer size to the specified number of resource performance entries.

The following example demonstrates the usage of these two methods.

function clear_resource_timings() {
  if (performance === undefined) {
    console.log("= performance.clearResourceTimings(): peformance NOT supported");
    return;
  }
  // Check if Performance.clearResourceTiming() is supported 
  console.log ("= Print performance.clearResourceTimings()");
  var supported = typeof performance.clearResourceTimings == "function";
  if (supported) {
    console.log("... Performance.clearResourceTimings() = supported");
    performance.clearResourceTimings();
  } else {
    console.log("... Performance.clearResourceTiming() = NOT supported");
    return;
  }
  // getEntries should now return zero
  var p = performance.getEntriesByType("resource");
  if (p.length == 0)  
    console.log("... Performance data buffer cleared");
  else
    console.log("... Performance data buffer NOT cleared (still have `" + p.length + "` items");
}

function set_resource_timing_buffer_size(n) {
  if (performance === undefined) {
    console.log("= performance.setResourceTimingBufferSize(): peformance NOT supported");
    return;
  }
  // Check if Performance.setResourceTimingBufferSize() is supported 
  console.log ("= performance.setResourceTimingBufferSize()");
  var supported = typeof performance.setResourceTimingBufferSize == "function";
  if (supported) {
    console.log("... Performance.setResourceTimingBufferSize() = supported");
    performance.setResourceTimingBufferSize(n);
  } else {
    console.log("... Performance.setResourceTimingBufferSize() = NOT supported");
  }
}

The Performance interface has a onresourcetimingbufferfull event handler that gets called (with an Event of type Event.type of "resourcetimingbufferfull") when the browser's resource performance entry buffer is full. The following code example sets a onresourcetimingbufferfull event callback in the init() function.

function buffer_full(event) {
  console.log("WARNING: Resource Timing Buffer is FULL!");
  set_resource_timing_buffer_size(200);
}

function init() {
  // load some image to trigger "resource" fetch events
  var image1 = new Image();
  image1.src = "https://developer.mozilla.org/static/img/opengraph-logo.png";
  var image2 = new Image();
  image2.src = "http://mozorg.cdn.mozilla.net/media/img/firefox/firefox-256.e2c1fc556816.jpg"
 
  // Set a callback if the resource buffer becomes filled
  performance.onresourcetimingbufferfull = buffer_full;
}

Coping with CORS

When CORS is in effect, many of the timing properties' values are returned as zero unless the server's access policy permits these values to be shared. This requires the server providing the resource to send the Timing-Allow-Origin HTTP response header with a value specifying the origin or origins which are allowed to get the restricted timestamp values.

The properties which are returned as 0 by default when loading a resource from a domain other than the one of the web page itself: redirectStart, redirectEnd, domainLookupStart, domainLookupEnd, connectStart, connectEnd, secureConnectionStart, requestStart, and responseStart.

See also