Movatterモバイル変換


[0]ホーム

URL:


This specification defines an interface for web applications to access the complete timing information for resources in a document.

Introduction

User latency is an important quality benchmark for Web Applications. While JavaScript-based mechanisms can provide comprehensive instrumentation for user latency measurements within an application, in many cases, they are unable to provide a complete end-to-end latency picture. This document introduces thePerformanceResourceTiming interface to allow JavaScript mechanisms to collect complete timing information related to resources on a document. Navigation Timing 2 [[NAVIGATION-TIMING-2]] extends this specification to provide additional timing information associated with a navigation.

For example, the following JavaScript shows a simple attempt to measure the time it takes to fetch a resource:

        <!doctype html>        <html>          <head>          </head>          <body onload="loadResources()">            <script>                function loadResources()                {                  var start = new Date().getTime();                  var image1 = new Image();                  var resourceTiming = function() {                      var now = new Date().getTime();                      var latency = now - start;                      alert("End to end resource fetch: " + latency);                  };                  image1.onload = resourceTiming;                  image1.src = 'https://www.w3.org/Icons/w3c_main.png';                }            </script>            <img src="https://www.w3.org/Icons/w3c_home.png">          </body>        </html>

Though this script can measure the time it takes to fetch a resource, it cannot break down the time spent in various phases. Further, the script cannot easily measure the time it takes to fetch resources described in markup.

To address the need for complete information on user experience, this document introduces thePerformanceResourceTiming interface. This interface allows JavaScript mechanisms to provide complete client-side latency measurements within applications. With this interface, the previous example can be modified to measure a user's perceived load time of a resource.

The following script calculates the amount of time it takes to fetch every resource in the page, even those defined in markup. This example assumes that this page is hosted on https://www.w3.org. One could further measure the amount of time it takes in every phase of fetching a resource with thePerformanceResourceTiming interface.

        <!doctype html>        <html>          <head>          </head>          <body onload="loadResources()">            <script>              function loadResources()              {                  var image1 = new Image();                  image1.onload = resourceTiming;                  image1.src = 'https://www.w3.org/Icons/w3c_main.png';              }              function resourceTiming()              {                  var resourceList = window.performance.getEntriesByType("resource");                  for (i = 0; i < resourceList.length; i++)                  {                      if (resourceList[i].initiatorType == "img")                      {                        alert("End to end resource fetch: " + (resourceList[i].responseEnd - resourceList[i].startTime));                      }                  }              }            </script>            <img src="https://www.w3.org/Icons/w3c_home.png">          </body>        </html>

Requirements phrased in the imperative as part of algorithms (such as "strip any leading space characters" or "return false and abort these steps") are to be interpreted with the meaning of the key word ("MUST", "SHOULD", "MAY", etc) used in introducing the algorithm.

Some conformance requirements are phrased as requirements on attributes, methods or objects. Such requirements are to be interpreted as requirements on user agents.

Conformance requirements phrased as algorithms or specific steps may be implemented in any manner, so long as the end result is equivalent. (In particular, the algorithms defined in this specification are intended to be easy to follow, and not intended to be performant.)

Terminology

The construction "aFoo object", whereFoo is actually an interface, is sometimes used instead of the more accurate "an object implementing the interfaceFoo.

Throughout this work, all time values are measured in milliseconds since the start of navigation of the document [[HR-TIME]]. For example, thestart of navigation of the document occurs at time 0.

This definition of time is based on the High Resolution Time specification [[HR-TIME]] and is different from the definition of time used in the Navigation Timing specification [[NAVIGATION-TIMING-2]], where time is measured in milliseconds since midnight of January 1, 1970 (UTC).

Resource Timing

Introduction

ThePerformanceResourceTiming interface facilitates timing measurement of [=fetch|fetched=] [=http(s) scheme|http(s)=] resources. For example, this interface is available for {{XMLHttpRequest}} objects [[XHR]], HTML elements [[HTML]] such as [^iframe^], [^img^], [^script^], [^object^], [^embed^] and [^link^] with the link type of [^link/rel/stylesheet^], SVG elements [[SVG11]] such assvg, and {{EventSource}}.

Resources Included in thePerformanceResourceTiming Interface

This section is non-normative.

Resource [=Request=]s [=fetch=]ed by a non-null [=request/client=] are included asPerformanceResourceTiming objects in the [=request/client=]'s [=environment settings object/global object=]'sPerformance Timeline, unless excluded from the timeline as part of the [=fetch|fetching process=]. Resources that are retrieved from HTTP cache are included asPerformanceResourceTiming objects in thePerformance Timeline. Resources for which the [=fetch=] was initiated, but was later aborted (e.g. due to a network error) are included asPerformanceResourceTiming objects in thePerformance Timeline, with their start and end timing.

Examples:

ThePerformanceResourceTiming Interface

          [Exposed=(Window,Worker)]          interface PerformanceResourceTiming : PerformanceEntry {              readonly attribute DOMString initiatorType;              readonly attribute DOMString deliveryType;              readonly attribute ByteString nextHopProtocol;              readonly attribute DOMHighResTimeStamp workerStart;              readonly attribute DOMHighResTimeStamp redirectStart;              readonly attribute DOMHighResTimeStamp redirectEnd;              readonly attribute DOMHighResTimeStamp fetchStart;              readonly attribute DOMHighResTimeStamp domainLookupStart;              readonly attribute DOMHighResTimeStamp domainLookupEnd;              readonly attribute DOMHighResTimeStamp connectStart;              readonly attribute DOMHighResTimeStamp connectEnd;              readonly attribute DOMHighResTimeStamp secureConnectionStart;              readonly attribute DOMHighResTimeStamp requestStart;              readonly attribute DOMHighResTimeStamp finalResponseHeadersStart;              readonly attribute DOMHighResTimeStamp firstInterimResponseStart;              readonly attribute DOMHighResTimeStamp responseStart;              readonly attribute DOMHighResTimeStamp responseEnd;              readonly attribute unsigned long long  transferSize;              readonly attribute unsigned long long  encodedBodySize;              readonly attribute unsigned long long  decodedBodySize;              readonly attribute unsigned short responseStatus;              readonly attribute RenderBlockingStatusType renderBlockingStatus;              readonly attribute DOMString contentType;              readonly attribute DOMString contentEncoding;              [Default] object toJSON();          };

APerformanceResourceTiming has an associated DOMStringinitiator type.

APerformanceResourceTiming has an associated DOMStringdelivery type.

APerformanceResourceTiming has an associated DOMStringrequested URL.

APerformanceResourceTiming has an associated DOMStringcache mode (the empty string, "local", or "validated").

APerformanceResourceTiming has an associated [=fetch timing info=]timing info.

APerformanceResourceTiming has an associated [=response body info=]resource info.

APerformanceResourceTiming has an associatedstatusresponse status.

APerformanceResourceTiming has an associated {{RenderBlockingStatusType}}render-blocking status.

WhentoJSON is called, run the [=default toJSON steps=] for {{PerformanceResourceTiming}}.

initiatorType getter steps are to return theinitiator type forthis.

`initiatorType` returns one of the following values:

  • "navigation", if the request is a [=navigation request=];
  • "body", if the request is a result of processing the [^body^] element'sbackground attribute that's already obsolete.
  • "css", if the request is a result of processing a CSSurl() directive such as@import url() orbackground: url(); [[CSS-VALUES]]

    Note: the request for a font resource specified with@font-face in CSS is a result of processing a CSS directive. Therefore, the `initiatorType` for this font resource is"css".

  • "script", if the request is a result of loading anyscript (a classic [^script^], a [=module script=], or a {{Worker}}).
  • "xmlhttprequest", if the request is a result of processing an {{XMLHttpRequest}};
  • "font", if the request is the result of processing fonts. This can happen when fonts request subsequent resources, e.g, when [[[INCREMENTAL_FONT_TRANSFER]]] is used.
  • "fetch", if the request is the result of processing the {{WindowOrWorkerGlobalScope/fetch()}} method;
  • "beacon", if the request is the result of processing the {{Navigator/sendBeacon()}} method; [[BEACON]]
  • "video", if the request is the result of processing the [^video^] element's [^video/poster^] or [^video/src^].
  • "audio", if the request is the result of processing the [^audio^] element's [^audio/src^].
  • "track", if the request is the result of processing the [^track^] element's [^track/src^].
  • "img", if the request is the result of processing the [^img^] element's [^img/src^] or [^img/srcset^].
  • "image", if the request is the result of processing theimage element. [[SVG2]]
  • "input", if the request is the result of processing an [^input^] element of [^input/type^] [^input/type/image^].
  • "ping", if the request is the result of processing an [^a^] element's [^a/ping^].
  • "iframe", if the request is the result of processing an [^iframe^]'s [^iframe/src^].
  • "frame", if the request is the result of loading a [^frame^].
  • "embed", if the request is the result of processing an [^embed^] element's [^embed/src^].
  • "link", if the request is the result of processing an [^link^] element.
  • "object", if the request is the result of processing an [^object^] element.
  • "early-hints", if the request is the result of processing an [[[EARLY_HINTS]]] response.
  • "other", if none of the above conditions match.

The setting of `initiatorType` is done at the different places where a resource timing entry is reported, such as the [=fetch=] standard.

deliveryType getter steps are to return thedelivery type forthis.

`deliveryType` returns one of the following values:

  • "cache", if thecache mode is not the empty string.
  • the empty string"", if none of the above conditions match.

This is expected to be expanded by future updates to this specification, e.g. to describe consuming preloaded resources and prefetched navigation requests.

TheworkerStart getter steps are toconvert fetch timestamp forthis'stiming info's [=fetch timing info/final service worker start time=] and therelevant global object forthis. See [=/HTTP fetch=] for more info.

TheredirectStart getter steps are toconvert fetch timestamp forthis'stiming info's [=fetch timing info/redirect start time=] and therelevant global object forthis. See [=/HTTP-redirect fetch=] for more info.

TheredirectEnd getter steps are toconvert fetch timestamp forthis'stiming info's [=fetch timing info/redirect end time=] and therelevant global object forthis. See [=/HTTP-redirect fetch=] for more info.

ThefetchStart getter steps are toconvert fetch timestamp forthis'stiming info's [=fetch timing info/post-redirect start time=] and therelevant global object forthis. See [=/HTTP fetch=] for more info.

ThedomainLookupStart getter steps are toconvert fetch timestamp forthis'stiming info's [=fetch timing info/final connection timing info=]'s [=connection timing info/domain lookup start time=] and therelevant global object forthis. SeeRecording connection timing info for more info.

ThedomainLookupEnd getter steps are toconvert fetch timestamp forthis'stiming info's [=fetch timing info/final connection timing info=]'s [=connection timing info/domain lookup end time=] and therelevant global object forthis. SeeRecording connection timing info for more info.

TheconnectStart getter steps are toconvert fetch timestamp forthis'stiming info's [=fetch timing info/final connection timing info=]'s [=connection timing info/connection start time=] and therelevant global object forthis. SeeRecording connection timing info for more info.

TheconnectEnd getter steps are toconvert fetch timestamp forthis'stiming info's [=fetch timing info/final connection timing info=]'s [=connection timing info/connection end time=] and therelevant global object forthis. SeeRecording connection timing info for more info.

ThesecureConnectionStart getter steps are toconvert fetch timestamp forthis'stiming info's [=fetch timing info/final connection timing info=]'s [=connection timing info/secure connection start time=] and therelevant global object forthis. SeeRecording connection timing info for more info.

ThenextHopProtocol getter steps are to [=/isomorphic decode=]this's [=PerformanceResourceTiming/timing info=]'s [=fetch timing info/final connection timing info=]'s [=connection timing info/ALPN negotiated protocol=]. SeeRecording connection timing info for more info.

Issue221 suggests to remove support for nextHopProtocol, as it can reveal details about the user's network configuration.

TherequestStart getter steps are toconvert fetch timestamp forthis'stiming info's [=fetch timing info/final network-request start time=] and therelevant global object forthis. See [=/HTTP fetch=] for more info.

ThefirstInterimResponseStart getter steps are toconvert fetch timestamp forthis'stiming info's [=fetch timing info/first interim network-response start time=] and therelevant global object forthis. See [=/HTTP fetch=] for more info.

ThefinalResponseHeadersStart getter steps are toconvert fetch timestamp forthis'stiming info's [=fetch timing info/final network-response start time=] and therelevant global object forthis. See [=/HTTP fetch=] for more info.

TheresponseStart getter steps are to returnthis's {{PerformanceResourceTiming/firstInterimResponseStart}} if it is not 0; Otherwisethis's {{PerformanceResourceTiming/finalResponseHeadersStart}}.

TheresponseEnd getter steps are toconvert fetch timestamp forthis'stiming info's [=fetch timing info/end time=] and therelevant global object forthis. See [=/fetch=] for more info.

TheencodedBodySize getter steps are to returnthis'sresource info's [=response body info/encoded size=].

ThedecodedBodySize getter steps are to returnthis'sresource info's [=response body info/decoded size=].

ThetransferSize getter steps are:

  1. Ifthis'scache mode is "local", then return 0.

  2. Ifthis'scache mode is "validated", then return 300.

  3. Returnthis'sresponse body info's [=response body info/encoded size=] plus 300.

    The constant number added to `transferSize` replaces exposing the total byte size of the HTTP headers, as that may expose the presence of certain cookies. Seethis issue.

TheresponseStatus getter steps are to returnthis'sresponse status.

`responseStatus` is determined in [=Fetch=]. For a cross-originno-cors request it would be 0 because the response would be anopaque filtered response.

ThecontentType getter steps are to returnthis'sresource info's [=response body info/content type=].

ThecontentEncoding getter steps are to returnthis'sresource info 's [=response body info/content encoding=].

TherenderBlockingStatus getter steps are to returnblocking ifthis'stiming info's [=fetch timing info/render-blocking=] is true; otherwisenon-blocking.

A user agent implementingPerformanceResourceTiming would need to include"resource" in {{PerformanceObserver/supportedEntryTypes}}. This allows developers to detect support for Resource Timing.

RenderBlockingStatusType enum

            enum RenderBlockingStatusType {                "blocking",                "non-blocking"            };

The values are defined as follows:

blocking
The resource can potentially block rendering.
non-blocking
The resource will not block rendering.

Extensions to thePerformance Interface

The user agent MAY choose to limit how many resources are included asPerformanceResourceTiming objects in thePerformance Timeline [[PERFORMANCE-TIMELINE-2]]. This section extends thePerformance interface to allow controls over the number ofPerformanceResourceTiming objects stored.

The recommended minimum number ofPerformanceResourceTiming objects is 250, though this may be changed by the user agent.setResourceTimingBufferSize can be called to request a change to this limit.

EachECMAScript global environment has:

partial interface Performance {          undefined clearResourceTimings ();          undefined setResourceTimingBufferSize (unsigned long maxSize);          attribute EventHandler onresourcetimingbufferfull;        };

ThePerformance interface is defined in [[HR-TIME]].

The methodclearResourceTimings runs the following steps:

  1. Remove allPerformanceResourceTiming objects in theperformance entry buffer.
  2. Setresource timing buffer current size to 0.

ThesetResourceTimingBufferSize method runs the following steps:

  1. Setresource timing buffer size limit to themaxSize parameter. If themaxSize parameter is less thanresource timing buffer current size, noPerformanceResourceTiming objects are to be removed from theperformance entry buffer.

The attributeonresourcetimingbufferfull is the event handler for theresourcetimingbufferfull event described below.

To check ifcan add resource timing entry, run the following steps:

  1. Ifresource timing buffer current size is smaller than resource timing buffer size limit, return true.
  2. Return false.

Toadd a PerformanceResourceTiming entrynew entry into theperformance entry buffer, run the following steps:

  1. Ifcan add resource timing entry returns true andresource timing buffer full event pending flag is false, run the following substeps:
    1. Addnew entry to theperformance entry buffer.
    2. Increaseresource timing buffer current size by 1.
    3. Return.
  2. Ifresource timing buffer full event pending flag is false, run the following substeps:
    1. Setresource timing buffer full event pending flag to true.
    2. Queue a task on the performance timeline task source to runfire a buffer full event.
  3. Addnew entry to theresource timing secondary buffer.
  4. Increaseresource timing secondary buffer current size by 1.

Tocopy secondary buffer, run the following steps:

  1. Whileresource timing secondary buffer is not empty andcan add resource timing entry returns true, run the following substeps:
    1. Letentry be the oldestPerformanceResourceTiming inresource timing secondary buffer.
    2. Addentry to the end ofperformance entry buffer.
    3. Incrementresource timing buffer current size by 1.
    4. Removeentry fromresource timing secondary buffer.
    5. Decrementresource timing secondary buffer current size by 1.

Tofire a buffer full event, run the following steps:

  1. Whileresource timing secondary buffer is not empty, run the following substeps:
    1. Letnumber of excess entries before beresource timing secondary buffer current size.
    2. Ifcan add resource timing entry returns false, then [=fire an event=] namedresourcetimingbufferfull at the {{Performance}} object.
    3. Runcopy secondary buffer.
    4. Letnumber of excess entries after beresource timing secondary buffer current size.
    5. Ifnumber of excess entries before is lower than or equalsnumber of excess entries after, then remove all entries fromresource timing secondary buffer, setresource timing secondary buffer current size to 0, and abort these steps.
  2. Setresource timing buffer full event pending flag to false.

    This means that if theresourcetimingbufferfull event handler does not add more room in the buffer than it adds resources to it, excess entries will be dropped from the buffer. Developers should make sure thatresourcetimingbufferfull event handlers callclearResourceTimings or extend the buffer sufficiently (by callingsetResourceTimingBufferSize).

Cross-origin Resources

As detailed in [=Fetch=], requests for cross-origin resources are included asPerformanceResourceTiming objects in thePerformance Timeline. If thetiming allow check algorithm fails for a cross-origin resource, the entry will be an [=create an opaque timing info|opaque entry=]. Such entries have most of their attributes masked in order to prevent leaking cross-origin data that isn't otherwise exposed. So, for an [=create an opaque timing info|opaque entry=], the following attributes will be set to zero: {{PerformanceResourceTiming/redirectStart}}, {{PerformanceResourceTiming/redirectEnd}}, {{PerformanceResourceTiming/workerStart}}, {{PerformanceResourceTiming/domainLookupStart}}, {{PerformanceResourceTiming/domainLookupEnd}}, {{PerformanceResourceTiming/connectStart}}, {{PerformanceResourceTiming/connectEnd}}, {{PerformanceResourceTiming/requestStart}}, {{PerformanceResourceTiming/firstInterimResponseStart}}, {{PerformanceResourceTiming/finalResponseHeadersStart}}, {{PerformanceResourceTiming/responseStart}}, {{PerformanceResourceTiming/secureConnectionStart}}, {{PerformanceResourceTiming/transferSize}}, {{PerformanceResourceTiming/encodedBodySize}}, and {{PerformanceResourceTiming/decodedBodySize}}. Further, the {{PerformanceResourceTiming/nextHopProtocol}} attribute will be set to the empty string.

Server-side applications may return theTiming-Allow-Origin HTTP response header to allow the User Agent to fully expose, to the document origin(s) specified, the values of attributes that would have been zero due to those cross-origin restrictions.

Timing-Allow-Origin Response Header

TheTiming-Allow-Origin HTTP response header field can be used to communicate a policy indicating origin(s) that may be allowed to see values of attributes that would have been zero due to the cross-origin restrictions. The header's value is represented by the following ABNF [[RFC5234]] (usingList Extension, [[RFC9110]]):

Timing-Allow-Origin = 1#(origin-or-null /wildcard )

The sender MAY generate multipleTiming-Allow-Origin header fields. The recipient MAY combine multipleTiming-Allow-Origin header fields by appending each subsequent field value to the combined field value in order, separated by a comma.

The user agent MAY still enforce cross-origin restrictions and set transferSize, encodedBodySize, and decodedBodySize attributes to zero, even with Timing-Allow-Origin HTTP response header fields. If it does, it MAY also set deliveryType to "".

TheTiming-Allow-Origin headers are processed inFETCH to compute the attributes accordingly.

The Timing-Allow-Origin header may arrive as part of a cached response. In case of cache revalidation, according toRFC 7234, the header's value may come from the revalidation response, or if not present there, from the original cached resource.

Issues222 and223 suggest to remove wildcard support from Timing-Allow-Origin in order to restrict its use.

IANA Considerations

This section registersTiming-Allow-Origin as aProvisional Message Header.

Header field name:
Timing-Allow-Origin
Applicable protocol:
http
Status:
provisional
Author/Change controller:
W3C
Specification document:

Resource Timing Attributes

This section is non-normative.

The following graph illustrates the timing attributes defined by the PerformanceResourceTiming interface. Attributes in parenthesis may not be available when [=fetch|fetching=] cross-origin resources. User agents may perform internal processing in between timings, which allow for non-normative intervals between timings.

This figure illustrates the timing attributes defined by thePerformanceResourceTiming interface. Attributes in parenthesis indicate that they may not be available if the resource fails thetiming allow check algorithm.
Resource Timing attributes

Creating a resource timing entry

Tomark resource timing given a [=/fetch timing info=] |timingInfo|, a DOMString |requestedURL|, a DOMString |initiatorType| aglobal object |global|, a string |cacheMode|, a [=/response body info=] |bodyInfo|, astatus |responseStatus|, and an optional [=string=] |deliveryType| (by default, the empty string), perform the following steps:

  1. Create aPerformanceResourceTiming object |entry| in |global|'s [=global object/realm=].
  2. Setup the resource timing entry for |entry|, given |initiatorType|, |requestedURL|, |timingInfo|, |cacheMode|, |bodyInfo|, |responseStatus|, and |deliveryType|.
  3. Queue |entry|.
  4. [=Add a PerformanceResourceTiming entry|Add=] |entry| to |global|'sperformance entry buffer.

Tosetup the resource timing entry forPerformanceResourceTiming |entry| given DOMString |initiatorType|, DOMString |requestedURL|, [=/fetch timing info=] |timingInfo|, a DOMString |cacheMode|, a [=response body info=] |bodyInfo|, astatus |responseStatus|, and an optional DOMString |deliveryType| (by default, the empty string), perform the following steps:

  1. Assert that |cacheMode| is the empty string, "local", or "validated".
  2. Let |global| be |entry|'s [=relevant global object=].
  3. [=initialize a PerformanceEntry|Initialize=] |entry| given the result ofconverting |timingInfo|'s [=fetch timing info/start time=] given |global|, "resource", |requestedURL|, and the result ofconverting |timingInfo|'s [=fetch timing info/end time=] given |global|.
  4. Set |entry|'sinitiator type to |initiatorType|.
  5. Set |entry|'srequested URL to |requestedURL|.
  6. Set |entry|'stiming info to |timingInfo|.
  7. Set |entry|'sresponse body info to |bodyInfo|.
  8. Set |entry|'scache mode to |cacheMode|.
  9. Set |entry|'sresponse status to |responseStatus|.
  10. If |deliveryType| is the empty string and |cacheMode| is not, then set |deliveryType| to "cache".
  11. Set |entry|'sdelivery type to |deliveryType|.

Toconvert fetch timestamp given {{DOMHighResTimeStamp}} |ts| andglobal object |global|, do the following:

  1. If |ts| is zero, return zero.
  2. Otherwise, return the [=relative high resolution coarse time=] given |ts| and |global|.

Security Considerations

ThePerformanceResourceTiming interface exposes timing information for a resource to any web page or worker that has requested that resource. To limit the access to thePerformanceResourceTiming interface, thesame origin policy is enforced by default and certain attributes are set to zero, as described in [=/HTTP fetch=]. Resource providers can explicitly allow all timing information to be collected for a resource by adding theTiming-Allow-Origin HTTP response header, which specifies the domains that are allowed to access the timing information.

Privacy Considerations

Statistical fingerprinting is a privacy concern where a malicious web site may determine whether a user has visited a third-party web site by measuring the timing of cache hits and misses of resources in the third-party web site. Though thePerformanceResourceTiming interface gives timing information for resources in a document, the load event on resources can already measure timing to determine cache hits and misses in a limited fashion, and the cross-origin restrictions in [=/HTTP Fetch=] prevent the leakage of any additional information.

Acknowledgments

Thanks to Anne Van Kesteren, Annie Sullivan, Arvind Jain, Boris Zbarsky, Darin Fisher, Jason Weber, Jonas Sicking, James Simonsen, Karen Anderson, Kyle Scholz, Nic Jansma, Philippe Le Hegaret, Sigbjørn Vik, Steve Souders, Todd Reifsteck, Tony Gentilcore, William Chan, and Alex Christensen for their contributions to this work.


[8]ページ先頭

©2009-2025 Movatter.jp