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

Implementers SHOULD be aware that this document is not stable. Implementers who are not taking part in the discussions are likely to find the specification changing out from under them in incompatible ways. Vendors interested in implementing this document before it eventually reaches the Candidate Recommendation stage SHOULD join the aforementioned mailing lists and take part in the discussions.

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 the PerformanceResourceTiming 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 the PerformanceResourceTiming 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 the PerformanceResourceTiming 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 id="image0" 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 "a Foo object", where Foo is actually an interface, is sometimes used instead of the more accurate "an object implementing the interface Foo.

The term DOM is used to refer to the API set made available to scripts in Web applications, and does not necessarily imply the existence of an actual Document object or of any other Node objects as defined in the [[DOM]] specification.

A DOM attribute is said to be getting when its value is being retrieved (such as by author script), and is said to be setting when a new value is assigned to it.

The term JavaScript is used to refer to ECMA262, rather than the official term ECMAScript, since the term JavaScript is more widely known. [[ECMASCRIPT]]

The term resource is used to refer to elements and any other user-initiated fetches throughout this specification. For example, a resource could originate from XMLHttpRequest objects [[XHR]], HTML elements [[HTML]] such as iframe, img, script, object, embed, and link with the link type of stylesheet, and SVG elements [[SVG11]] such as svg.

The term cross-origin is used to mean non same origin.

The term current document refers to the document associated with the Window object's newest Document object.

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

The term current time refers to the number of milliseconds since the start of navigation of the document until the current moment in time.

This definition of time is based on the High Resolution Time specification [[HR-TIME-2]] 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

The PerformanceResourceTiming interface facilitates timing measurement of downloadable 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 stylesheet, and SVG elements [[SVG11]] such as svg.

Resources Included in the PerformanceResourceTiming Interface

All resource Requests fetched by a non-null client MUST be included as PerformanceResourceTiming objects in the client's global object's Performance Timeline, unless excluded from the timeline as part of the [=fetch|fetching process=]. Resources that are retrieved from relevant application caches or local resources MUST be included as PerformanceResourceTiming objects in the Performance Timeline [[PERFORMANCE-TIMELINE-2]]. Resources for which the fetch was initiated, but was later aborted (e.g. due to a network error) MAY be included as PerformanceResourceTiming objects in the Performance Timeline and MUST contain initialized attribute values for processed substeps of the [=fetch|fetching process=].

The rest of this section is non-normative.

Examples:

The PerformanceResourceTiming Interface

[Exposed=(Window,Worker)]
interface PerformanceResourceTiming : PerformanceEntry {
    readonly        attribute DOMString           initiatorType;
    readonly        attribute DOMString           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 responseStart;
    readonly        attribute DOMHighResTimeStamp responseEnd;
    readonly        attribute unsigned long long  transferSize;
    readonly        attribute unsigned long long  encodedBodySize;
    readonly        attribute unsigned long long  decodedBodySize;
    [Default] object toJSON();
};

A PerformanceResourceTiming has an associated DOMString initiator type.

A PerformanceResourceTiming has an associated DOMString requested URL.

A PerformanceResourceTiming has an associated DOMString cache mode (the empty string or "local").

A PerformanceResourceTiming has an associated [=fetch timing info=] timing info.

The PerformanceResourceTiming interface participates in the Performance Timeline and extends the following attributes of the PerformanceEntry interface:

name
The name getter steps are to return this's requested URL.
entryType
The entryType getter steps are to return the DOMString "resource".
startTime

The startTime getter steps are to convert fetch timestamp for this's timing info's [=fetch timing info/start time=] and this's relevant global object.

duration

The duration getter steps are to return this's timing info's [=fetch timing info/end time=] minus this's timing info's [=fetch timing info/start time=].

When toJSON is called, run [[WEBIDL]]'s default toJSON operation.

initiatorType getter steps are to return the initiator type for this.

The workerStart getter steps are to convert fetch timestamp for this's timing info's [=fetch timing info/final service worker start time=] and the relevant global object for this. See [=/HTTP fetch=] for more info.

The redirectStart getter steps are to convert fetch timestamp for this's timing info's [=fetch timing info/redirect start time=] and the relevant global object for this. See [=/HTTP-redirect fetch=] for more info.

The redirectEnd getter steps are to convert fetch timestamp for this's timing info's [=fetch timing info/redirect end time=] and the relevant global object for this. See [=/HTTP-redirect fetch=] for more info.

The fetchStart getter steps are to convert fetch timestamp for this's timing info's [=fetch timing info/post-redirect start time=] and the relevant global object for this. See [=/HTTP fetch=] for more info.

The domainLookupStart getter steps are to convert fetch timestamp for this's timing info's [=fetch timing info/final connection timing info=]'s [=connection timing info/domain lookup start time=] and the relevant global object for this. See Recording connection timing info for more info.

The domainLookupEnd getter steps are to convert fetch timestamp for this's timing info's [=fetch timing info/final connection timing info=]'s [=connection timing info/domain lookup end time=] and the relevant global object for this. See Recording connection timing info for more info.

The connectStart getter steps are to convert fetch timestamp for this's timing info's [=fetch timing info/final connection timing info=]'s [=connection timing info/connection start time=] and the relevant global object for this. See Recording connection timing info for more info.

The connectEnd getter steps are to convert fetch timestamp for this's timing info's [=fetch timing info/final connection timing info=]'s [=connection timing info/connection end time=] and the relevant global object for this. See Recording connection timing info for more info.

The secureConnectionStart getter steps are to convert fetch timestamp for this's timing info's [=fetch timing info/final connection timing info=]'s [=connection timing info/secure connection start time=] and the relevant global object for this. See Recording connection timing info for more info.

The nextHopProtocol getter steps are to [=/isomorphic decode=] this's timing info's [=fetch timing info/final connection timing info=]'s [=connection timing info/ALPN negotiated protocol=]. See Recording connection timing info for more info.

The requestStart getter steps are to convert fetch timestamp for this's timing info's [=fetch timing info/final network-request start time=] and the relevant global object for this. See [=/HTTP fetch=] for more info.

The responseStart getter steps are to convert fetch timestamp for this's timing info's [=fetch timing info/final network-response start time=] and the relevant global object for this. See [=/HTTP fetch=] for more info.

The responseEnd getter steps are to convert fetch timestamp for this's timing info's [=fetch timing info/end time=] and the relevant global object for this. See [=/fetch=] for more info.

The encodedBodySize getter steps are to return this's timing info's [=fetch timing info/encoded body size=].

The decodedBodySize getter steps are to return this's timing info's [=fetch timing info/decoded body size=].

The transferSize getter steps are to perform the following steps:

  1. If this's cache mode is "local", then return 0.

  2. Return this's timing info's [=fetch timing info/encoded body 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. See this issue.

A user agent implementing PerformanceResourceTiming would need to include "resource" in supportedEntryTypes. This allows developers to detect support for Resource Timing.

Extensions to the Performance Interface

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

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

Each ECMAScript global environment has:

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

The Performance interface is defined in [[HR-TIME-2]].

The method clearResourceTimings runs the following steps:

  1. Remove all PerformanceResourceTiming objects in the performance entry buffer.
  2. Set resource timing buffer current size to 0.

The setResourceTimingBufferSize method runs the following steps:

  1. Set resource timing buffer size limit to the maxSize parameter. If the maxSize parameter is less than resource timing buffer current size, no PerformanceResourceTiming objects are to be removed from the performance entry buffer.

The attribute onresourcetimingbufferfull is the event handler for the resourcetimingbufferfull event described below.

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

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

To add a PerformanceResourceTiming entry into the performance entry buffer, run the following steps:

  1. Let new entry be the input PerformanceEntry to be added.
  2. If can add resource timing entry returns true and resource timing buffer full event pending flag is false, run the following substeps:
    1. Add new entry to the performance entry buffer.
    2. Increase resource timing buffer current size by 1.
    3. Return.
  3. If resource timing buffer full event pending flag is false, run the following substeps:
    1. Set resource timing buffer full event pending flag to true.
    2. Queue a task on the performance timeline task source to run fire a buffer full event.
  4. Add new entry to the resource timing secondary buffer.
  5. Increase resource timing secondary buffer current size by 1.

To copy secondary buffer, run the following steps:

  1. While resource timing secondary buffer is not empty and can add resource timing entry returns true, run the following substeps:
    1. Let entry be the oldest PerformanceResourceTiming in resource timing secondary buffer.
    2. Add entry to the end of performance entry buffer.
    3. Increment resource timing buffer current size by 1.
    4. Remove entry from resource timing secondary buffer.
    5. Decrement resource timing secondary buffer current size by 1.

To fire a buffer full event, run the following steps:

  1. While resource timing secondary buffer is not empty, run the following substeps:
    1. Let number of excess entries before be resource timing secondary buffer current size.
    2. If can add resource timing entry returns false, then fire an event named resourcetimingbufferfull at the Performance object.
    3. Run copy secondary buffer.
    4. Let number of excess entries after be resource timing secondary buffer current size.
    5. If number of excess entries before is lower than or equals number of excess entries after, then remove all entries from resource timing secondary buffer, set resource timing secondary buffer current size to 0, and abort these steps.
  2. Set resource timing buffer full event pending flag to false.

    This means that if the resourcetimingbufferfull 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 that resourcetimingbufferfull event handlers call clearResourceTimings or extend the buffer sufficiently (by calling setResourceTimingBufferSize).

Cross-origin Resources

As detailed in [=Fetch=], cross-origin resources are included as PerformanceResourceTiming objects in the Performance Timeline. If the timing allow check algorithm fails for a resource, the following attributes of its PerformanceResourceTiming object are set to zero: {{PerformanceResourceTiming/redirectStart}}, {{PerformanceResourceTiming/redirectEnd}}, {{PerformanceResourceTiming/domainLookupStart}}, {{PerformanceResourceTiming/domainLookupEnd}}, {{PerformanceResourceTiming/connectStart}}, {{PerformanceResourceTiming/connectEnd}}, {{PerformanceResourceTiming/requestStart}}, {{PerformanceResourceTiming/responseStart}}, {{PerformanceResourceTiming/secureConnectionStart}}, {{PerformanceResourceTiming/transferSize}}, {{PerformanceResourceTiming/encodedBodySize}}, and {{PerformanceResourceTiming/decodedBodySize}}.

Server-side applications may return the Timing-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 the cross-origin restrictions previously specified in this section.

Timing-Allow-Origin Response Header

The Timing-Allow-Origin HTTP response header field can be used to communicate a policy indicating origin(s) that are 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]] (using List Extension, [[RFC7230]]):

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

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

The Timing-Allow-Origin headers are processed in FETCH to compute the attributes accordingly.

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

IANA Considerations

This section registers Timing-Allow-Origin as a Provisional 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 the PerformanceResourceTiming interface. Attributes in parenthesis indicate that they may not be available if the resource fails the timing allow check algorithm.
Resource Timing attributes

Creating a resource timing entry

To mark resource timing given a [=/fetch timing info=] |timingInfo|, a DOMString |requestedURL|, a DOMString |initiatorType| a global object |global|, and a string |cacheMode|, perform the following steps:

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

To setup the resource timing entry for PerformanceResourceTiming |entry| given DOMString |initiatorType|, DOMString |requestedURL|, [=/fetch timing info=] |timingInfo|, and a DOMString |cacheMode|, perform the following steps:

  1. Assert that |cacheMode| is the empty string or "local".
  2. Set |entry|'s initiator type to |initiatorType|.
  3. Set |entry|'s requested URL to |requestedURL|.
  4. Set |entry|'s timing info to |timingInfo|.
  5. Set |entry|'s cache mode to |cacheMode|.

To convert fetch timestamp given {{DOMHighResTimeStamp}} |ts| and global 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|.

Privacy and Security

The PerformanceResourceTiming interface exposes timing information for a resource to any web page or worker that has requested that resource. To limit the access to the PerformanceResourceTiming interface, the same 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 the Timing-Allow-Origin HTTP response header, which specifies the domains that are allowed to access the timing information.

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 the PerformanceResourceTiming interface gives timing information for resources in a document, the cross-origin restrictions in in [=/HTTP Fetch=] prevent making this privacy concern any worse than it is today using the load event on resources to measure timing to determine cache hits and misses.

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 and William Chan for their contributions to this work.