aboutsummaryrefslogtreecommitdiff
path: root/files/zh-cn/web/api/resource_timing_api
diff options
context:
space:
mode:
authorPeter Bengtsson <mail@peterbe.com>2020-12-08 14:40:17 -0500
committerPeter Bengtsson <mail@peterbe.com>2020-12-08 14:40:17 -0500
commit33058f2b292b3a581333bdfb21b8f671898c5060 (patch)
tree51c3e392513ec574331b2d3f85c394445ea803c6 /files/zh-cn/web/api/resource_timing_api
parent8b66d724f7caf0157093fb09cfec8fbd0c6ad50a (diff)
downloadtranslated-content-33058f2b292b3a581333bdfb21b8f671898c5060.tar.gz
translated-content-33058f2b292b3a581333bdfb21b8f671898c5060.tar.bz2
translated-content-33058f2b292b3a581333bdfb21b8f671898c5060.zip
initial commit
Diffstat (limited to 'files/zh-cn/web/api/resource_timing_api')
-rw-r--r--files/zh-cn/web/api/resource_timing_api/index.html76
-rw-r--r--files/zh-cn/web/api/resource_timing_api/using_the_resource_timing_api/index.html203
2 files changed, 279 insertions, 0 deletions
diff --git a/files/zh-cn/web/api/resource_timing_api/index.html b/files/zh-cn/web/api/resource_timing_api/index.html
new file mode 100644
index 0000000000..238135639e
--- /dev/null
+++ b/files/zh-cn/web/api/resource_timing_api/index.html
@@ -0,0 +1,76 @@
+---
+title: Resource Timing API
+slug: Web/API/Resource_Timing_API
+translation_of: Web/API/Resource_Timing_API
+---
+<div>{{DefaultAPISidebar("Resource Timing API")}}</div>
+
+<div> </div>
+
+<div>通过<strong><code>Resource Timing API</code></strong>可以获取和分析应用资源加载的详细网络计时数据, 应用程序可以</div>
+
+<div>使用时间度量标准来确定加载特定资源所需要的时间, 比如 {{domxref("XMLHttpRequest")}}, {{SVGElement("SVG","SVG element")}}, 图片, 或者脚本.</div>
+
+<div> </div>
+
+<p><code><strong>Resource Timing API</strong></code>为网络事件(如重定向的开始和结束事件, DNS查找的开始和结束事件, 请求开始, 响应开始和结束时间等)生成有高分辨率时间戳( {{domxref("DOMHighResTimeStamp","high-resolution timestamps", "", 1)}} )的资源加载时间线, 并提供了资源大小和资源类型.</p>
+
+<p>本文档是Resource Timing API的概述. 更多详细信息, 请查阅每个接口的参考说明, <a href="/Web/API/Resource_Timing/Using_Resource_Timing">Using Resource Timing</a> 和 {{anch("See_Also","附录")}} 的参考链接. 有关资源时序处理模型的图示,请参阅 <a href="https://w3c.github.io/resource-timing/#process">resource timing phases</a> .</p>
+
+<p class="note"><code>PerformanceResourceTiming</code> 接口只统计{{domxref("PerformanceEntry","performance entries", "", 1)}} 中 {{domxref("PerformanceEntry.entryType","entryType")}} 为"<code>resource</code>"类型的 {{domxref("PerformanceEntry")}}</p>
+
+<h2 id="高分辨率时间戳">高分辨率时间戳</h2>
+
+<p>一些 <code><strong>Resource Timing</strong></code> 属性返回高分辨率时间戳, 顾名思义, 代表了高分辨率的时间点. 高分辨率时间戳类型是<code>{{domxref("DOMHighResTimeStamp")}}</code>, 用双精度数字(double)表示, 它的值是一个离散的时间点或者两个离散时间点之间的时间差.</p>
+
+<p><code>DOMHighResTimeStamp</code>的单位是毫秒(ms), 并且应该可以准确到 5 微秒(µs). 但是, 如果浏览器无法以提供精确到5微秒的时间值(如软硬件限制), 则可以将该值表示为以毫秒为单位的精确到毫秒的时间。</p>
+
+<h2 id="资源载入时间戳">资源载入时间戳</h2>
+
+<p>应用程序可以获得用于加载资源的各个阶段的时间戳. 处理模型中的第一个属性是 {{domxref("PerformanceEntry.startTime","startTime")}} , 它在资源加载过程开始之前立即返回时间. {{domxref("PerformanceResourceTiming.fetchStart","fetchStart")}} 跟踪和重定向处理(如果适用),并在DNS查找之前进行. 下个阶段是{{domxref('PerformanceResourceTiming.connectStart','connectStart')}} 和 {{domxref('PerformanceResourceTiming.connectEnd','connectEnd')}} 分别是开始连接到服务器和连接建立完成的时间戳. 最后三个按顺序分别是: {{domxref('PerformanceResourceTiming.requestStart','requestStart')}} - 在浏览器开始向服务器请求资源时; {{domxref('PerformanceResourceTiming.responseStart','responseStart')}} - 资源请求首包返回时; and {{domxref('PerformanceResourceTiming.responseEnd','responseEnd')}} - 资源全部接收完成时. 如果资源是通过安全连接加载的 {{domxref('PerformanceResourceTiming.secureConnectionStart','secureConnectionStart')}} 的值将会在connectStart和connectEnd之间.</p>
+
+<div class="note">
+<p>当 {{Glossary("CORS")}} 生效时, 除非服务器的访问策略允许共享这些值,否则这些值中的许多将返回为零. 这需要提供资源的服务器发送 <code>Timing-Allow-Origin</code> HTTP 响应头并且指定origin[s]来源才能允许获取这些被限制的时间戳 .</p>
+
+<p>在非web页面本身的域名下,这些属性在默认都会返回0值 : <code>redirectStart</code>, <code>redirectEnd</code>, <code>domainLookupStart</code>, <code>domainLookupEnd</code>, <code>connectStart</code>, <code>connectEnd</code>, <code>secureConnectionStart</code>, <code>requestStart</code>, 和 <code>responseStart</code>.</p>
+</div>
+
+<p>The <code>{{domxref("PerformanceResourceTiming")}}</code> interface also includes several network timing properties. The {{domxref("PerformanceResourceTiming.redirectStart","redirectStart")}} and {{domxref("PerformanceResourceTiming.redirectEnd","redirectEnd")}} properties return {{domxref("DOMHighResTimeStamp","timestamps")}} for redirect start and end times, respectively. Likewise, the The {{domxref("PerformanceResourceTiming.domainLookupStart","domainLookupStart")}} and {{domxref("PerformanceResourceTiming.domainLookupEnd","domainLookupEnd")}} properties return {{domxref("DOMHighResTimeStamp","timestamps")}} for DNS lookup start and end times, respectively.</p>
+
+<p><em>This would be a nice place to have a diagram showing the relationships between these segments of the resource loading time.</em></p>
+
+<h2 id="Resource_size">Resource size</h2>
+
+<p> {{domxref("PerformanceResourceTiming")}}接口有三个属性用来获取一个资源的数据大小。 {{domxref('PerformanceResourceTiming.transferSize','transferSize')}} 属性返回所获得的资源大小,包含响应头加上响应体。</p>
+
+<p>The {{domxref('PerformanceResourceTiming.encodedBodySize','encodedBodySize')}} property returns the size (in octets) received from the fetch (HTTP or cache), of the <em>payload body</em>, <strong>before</strong> removing any applied content-codings. {{domxref('PerformanceResourceTiming.decodedBodySize','decodedBodySize')}} returns the size (in octets) received from the fetch (HTTP or cache) of the <em>message body</em>, <strong>after</strong> removing any applied content-codings.</p>
+
+<h2 id="Other_properties">Other properties</h2>
+
+<p>The {{domxref('PerformanceResourceTiming.nextHopProtocol','nextHopProtocol')}} property returns the <em>network protocol</em> used to fetch the resource.</p>
+
+<p>The {{domxref('PerformanceResourceTiming.initiatorType','initiatorType')}} property returns the <em>type</em> of resource that initiated the performance entry such as "<code>css</code>" for a CSS resource, "<code>xmlhttprequest</code>" for an XMLHttpRequest and "<code>img</code>" for an image (such as a JPEG).</p>
+
+<p>If the current context is a {{domxref("Worker","worker")}}, the {{domxref('PerformanceResourceTiming.workerStart','workerStart')}} property can be used to obtain a {{domxref("DOMHighResTimeStamp")}} when the worker was started.</p>
+
+<h2 id="Methods">Methods</h2>
+
+<p>The Resource Timing API includes two methods that extend the {{domxref("Performance")}} interface. The {{domxref("Performance.clearResourceTimings","clearResourceTimings()")}} method removes all "<code>resource</code>" type performance entries from the browser's <em>resource</em> performance entry buffer. The {{domxref("Performance.setResourceTimingBufferSize","setResourceTimingBufferSize()")}} method sets the resource performance entry buffer size to the specified number of resource {{domxref("PerformanceEntry","performance entries")}}.</p>
+
+<p>The {{domxref("PerformanceResourceTiming")}} interface's {{domxref("PerformanceResourceTiming.toJSON","toJSON()")}} method returns a JSON serialization of a "<code>resource</code>" type {{domxref("PerformanceEntry","performance entry")}}.</p>
+
+<h2 id="Implementation_status">Implementation status</h2>
+
+<p>As shown in the {{domxref("PerformanceResourceTiming")}} interface's <a href="/Web/API/PerformanceResourceTiming#Browser_compatibility">Browser Compatibility</a> table, most of these interfaces are broadly implemented by desktop browsers. However, note that some properties have little to no implementation so see each property's "Browser compatibility" section for more specific interoperability data.</p>
+
+<p>To test your browser's support for these interfaces, run the <code><a href="https://mdn.github.io/dom-examples/performance-apis/perf-api-support.html">perf-api-support</a></code> application.</p>
+
+<h2 id="附录">附录</h2>
+
+<ul>
+ <li><a href="https://w3c.github.io/resource-timing/">Resource Timing Standard</a>; W3C Editor's Draft</li>
+ <li><a href="http://caniuse.com/#search=resource-timing">CanIUse data</a></li>
+ <li><a href="http://www.stevesouders.com/blog/2014/08/21/resource-timing-practical-tips/">Resource Timing practical tips</a>; Steve Souders; 2014 August 21</li>
+ <li><a href="http://googledevelopers.blogspot.ca/2013/12/measuring-network-performance-with.html">Measuring network performance with Resource Timing API</a>; Ilya Grigorik; 2013 December 11</li>
+ <li><a href="http://siusin.github.io/perf-timing-primer/">A Primer for Web Performance Timing APIs</a>; Xiaoqian Wu; W3C Editor's Draft</li>
+</ul>
diff --git a/files/zh-cn/web/api/resource_timing_api/using_the_resource_timing_api/index.html b/files/zh-cn/web/api/resource_timing_api/using_the_resource_timing_api/index.html
new file mode 100644
index 0000000000..ed1981d7e0
--- /dev/null
+++ b/files/zh-cn/web/api/resource_timing_api/using_the_resource_timing_api/index.html
@@ -0,0 +1,203 @@
+---
+title: Using the Resource Timing API
+slug: Web/API/Resource_Timing_API/Using_the_Resource_Timing_API
+translation_of: Web/API/Resource_Timing_API/Using_the_Resource_Timing_API
+---
+<div>{{DefaultAPISidebar("Resource Timing API")}}</div>
+
+<p><strong>Resource Timing API</strong> 提供了获取和分析应用程序<em>资源</em>加载的详细网络计时数据的一种途径。应用可以使用一些可量化的时间度量标准,如加载特定资源的时长。这些资源可能是 {{domxref("XMLHttpRequest")}}, {{SVGElement("SVG","SVG element")}}、图片、脚本等等。</p>
+
+<p>这个接口提供了使用 {{domxref("DOMHighResTimeStamp","高精度时间戳")}} 度量的资源加载时间轴。此时间轴包含众多网络事件的时间,如重定向开始和结束时间,开始请求资源时间,DNS查询开始和结束时间,响应开始和结束时间等等。也包含了请求到的资源的大小、请求发起者的<em>类型</em>。</p>
+
+<p>这篇文档展示了如何使用 Resource Timing 接口。获取更详细的信息或示例,请查看每个接口的文档和{{anch("See also")}}章节。</p>
+
+<p><a href="https://mdn.github.io/dom-examples/performance-apis/Using_the_Resource_Timing_API.html">Github</a>上有一个真实的例子,这里是它的源码 <a href="https://github.com/mdn/dom-examples/blob/master/performance-apis/Using_the_Resource_Timing_API.html">source code</a>. 欢迎提pull request和<a href="https://github.com/mdn/dom-examples/issues">报告bug</a>。</p>
+
+<h2 id="资源加载的各个阶段">资源加载的各个阶段</h2>
+
+<p>应用可以获取到资源加载的各个阶段的时间戳,如重定向、DNS查询、TCP连接建立。这些阶段和他们的属性名在图1中列出。</p>
+
+<p><img alt="Graphic of Resource Timing timestamps" src="https://mdn.mozillademos.org/files/12093/ResourceTiming-TimeStamps.jpg" style="height: 540px; width: 720px;"><br>
+ 图 1. Resource timing 属性</p>
+
+<p>应用开发者可以使用这些属性值去计算某个阶段的耗时长度,用来帮助诊断性能问题。</p>
+
+<h2 id="计算资源加载各阶段的时间">计算资源加载各阶段的时间</h2>
+
+<p>接下来的这段例子展示了用 Resource timing 属性去计算以下阶段的耗时:重定向 ({{domxref("PerformanceResourceTiming.redirectStart","redirectStart")}} 和 {{domxref("PerformanceResourceTiming.redirectEnd","redirectEnd")}} ),DNS查询({{domxref("PerformanceResourceTiming.domainLookupStart","domainLookupStart")}} 和 {{domxref("PerformanceResourceTiming.domainLookupEnd","domainLookupEnd")}}),TCP握手 ({{domxref('PerformanceResourceTiming.connectStart','connectStart')}} 和 {{domxref('PerformanceResourceTiming.connectEnd','connectEnd')}}), 响应 ({{domxref('PerformanceResourceTiming.responseStart','responseStart')}} 和 {{domxref('PerformanceResourceTiming.responseEnd','responseEnd')}})。 这段例子也计算了从开始获取资源和请求开始(分别为{{domxref("PerformanceResourceTiming.fetchStart","fetchStart")}} and {{domxref("PerformanceResourceTiming.requestStart","requestStart")}})到响应结束 ({{domxref('PerformanceResourceTiming.responseEnd','responseEnd')}}) 的时间.</p>
+
+<pre class="brush: js notranslate">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 &lt;= 0) {
+    console.log("= Calculate Load Times: there are NO `resource` performance records");
+    return;
+  }
+
+  console.log("= Calculate Load Times");
+  for (var i=0; i &lt; 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 &gt; 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 &gt; 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 &gt; 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 &gt; 0) ? (resources[i].responseEnd - resources[i].startTime) : "0";
+    console.log("... Start until response end time = " + t);
+  }
+}
+</pre>
+
+<h2 id="Size_matters">Size matters?</h2>
+
+<p>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 {{domxref("PerformanceResourceTiming")}} interface has three properties that can be used to obtain size data about a resource. The {{domxref('PerformanceResourceTiming.transferSize','transferSize')}} property returns the size (in octets) of the fetched resource including the response header fields plus the response payload body. The {{domxref('PerformanceResourceTiming.encodedBodySize','encodedBodySize')}} property returns the size (in octets) received from the fetch (HTTP or cache), of the <em>payload body</em>, <strong>before</strong> removing any applied content-codings. {{domxref('PerformanceResourceTiming.decodedBodySize','decodedBodySize')}} returns the size (in octets) received from the fetch (HTTP or cache) of the <em>message body</em>, <strong>after</strong> removing any applied content-codings.</p>
+
+<p>The following example demonstrates using these three properties.</p>
+
+<pre class="brush: js notranslate">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 &lt; 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");
+ }
+}
+</pre>
+
+<h2 id="Managing_the_resource_buffer">Managing the resource buffer</h2>
+
+<p>Although the browser is required to support at least 150 resource timing performance entries in its <em>resource timing buffer</em>, 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 {{domxref("Performance")}} interface. The {{domxref("Performance.clearResourceTimings","clearResourceTimings()")}} method removes all "<code>resource</code>" type performance entries from the browser's resource performance entry buffer. The {{domxref("Performance.setResourceTimingBufferSize","setResourceTimingBufferSize()")}} method sets the resource performance entry buffer size to the specified number of resource {{domxref("PerformanceEntry","performance entries")}}.</p>
+
+<p>The following example demonstrates the usage of these two methods.</p>
+
+<pre class="brush: js notranslate">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");
+ }
+}
+</pre>
+
+<p>The {{domxref("Performance")}} interface has a {{domxref("Performance.onresourcetimingbufferfull","onresourcetimingbufferfull")}} event handler that gets called (with an {{domxref("Event")}} of type {{domxref("Event.type")}} of "{{event("resourcetimingbufferfull")}}") when the browser's resource performance entry buffer is full. The following code example sets a {{domxref("Performance.onresourcetimingbufferfull","onresourcetimingbufferfull")}} event callback in the <code>init()</code> function.</p>
+
+<pre class="brush: js notranslate">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;
+}
+</pre>
+
+<h2 id="Coping_with_CORS">Coping with CORS</h2>
+
+<p>When {{Glossary("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 {{httpheader("Timing-Allow-Origin")}} HTTP response header with a value specifying the origin or origins which are allowed to get the restricted timestamp values.</p>
+
+<div class="note">
+<p>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: <code>redirectStart</code>, <code>redirectEnd</code>, <code>domainLookupStart</code>, <code>domainLookupEnd</code>, <code>connectStart</code>, <code>connectEnd</code>, <code>secureConnectionStart</code>, <code>requestStart</code>, and <code>responseStart</code>.</p>
+</div>
+
+<h2 id="See_also">See also</h2>
+
+<ul>
+ <li><a href="https://developer.mozilla.org/en-US/docs/Tools/Performance">Firefox Performance Tool</a></li>
+ <li><a href="https://w3c.github.io/resource-timing/">Resource Timing Standard</a>; W3C Editor's Draft</li>
+ <li><a href="http://www.stevesouders.com/blog/2014/08/21/resource-timing-practical-tips/">Resource Timing practical tips</a>; Steve Souders; 2014 August 21</li>
+ <li><a href="http://googledevelopers.blogspot.ca/2013/12/measuring-network-performance-with.html">Measuring network performance with Resource Timing API</a>; Ilya Grigorik; 2013 December 11</li>
+</ul>