Web development comes with the browser every day, showing loads from all kinds of resources. Performance optimization must have measure, the so-called “all have according to the (data) to follow”, so PerformanceResourceTiming is you not to be missed an official API.
We never produce official documents, we only do the porter of official documents.
This melon sentiment translation, appropriate annotation, smile summary, to share, please correct. Writing is not easy, praise 👍 encourage!
Original: https://www.w3.org/TR/resource-timing/#dom-performanceresourcetiming
preface
introduce
User latency is an important quality benchmark for Web applications. While javascript-based mechanisms can provide a comprehensive tool for measuring user delay in an application, in many cases they do not provide a complete end-to-end delay profile. This document introduces the PerformanceResourceTiming interface: allows JavaScript to collect complete timing information associated with the document resources.
For example, the following shows how to simply try to fetch a resource using JavaScript:
<! 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 qresource 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>
Copy the code
Although this script can capture the time spent on the resource, it cannot decompose the time spent in the phases. In addition, the script cannot easily capture the time spent on the resource described in the tag.
In order to meet the requirements of complete information about the user experience, this document introduces PerformanceResourceTiming. This interface allows JavaScript to provide complete client-side delay measurements in applications. Using this interface, you can modify the previous example to measure user-perceived resource load times.
<! 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>
Copy the code
Document specification
- Ps: This paragraph for the specification of the article, optional skip.
Except for markers, guides, charts, examples, and notes that are not normative. All other content in this specification is in compliance with the specification standards.
The keywords may, must, must not and should should be interpreted as described in RFC2119.
Some of the algorithm commands should require the following :(for example, “delete any leading whitespace characters” or “return false and abort these steps”) use the meaning of keywords (” must “, “should”, “may”, etc.) to introduce the algorithm.
Some requirements for consistent representation of properties, methods, or objects should be analogous to requirements for clients.
The consistency requirements for an algorithm or a particular step can be expressed in any way as long as the end result is equivalent. (The algorithms defined in this specification are intended to conform to the standard, not to be unconventional.)
As described in the Web IDL specification, IDL fragments in this specification must be interpreted as conforming to the REQUIREMENTS of IDL fragments. WebIDL
Expression of interpretation
- Ps: This paragraph explains the possible ambiguity in some document expressions, which can be skipped.
Sometimes the use of Foo actually means the construction of the interface “a Foo object” rather than the precise “implementation of the Foo interface object”.
Expresses the SET of apis that the DOM is used to represent scripts in a Web application, and not necessarily the actual Document object or any other object defined in the NodeDOM specification. DOM
A DOM property is said to be “getting value” when it is getting a value and “setting” when it is assigning a new value.
Because JavaScript is more widely known, express JavaScript is used to represent ECMA262, not the official expression ECMAScript. ECMA-262
Throughout the specification, the term “resource” is used to refer to elements and any other actively acquired by the user. For example, resources can be powered from XMLHttpRequest objects, HTML elements HTML51 (such as iframe, IMG, scripts, objects, embedded and links with style sheet link types), and SVG elements SVG11.
The expression “across origin” is used to refer to different origin points.
The statement “current Document” refers to the Document associated with the Window object’s latest Document object.
Throughout the work, all TIME values are in milliseconds since you started browsing the document HR-time 2.
The term “current time” refers to the number of milliseconds between the start of navigation in the document and the current point in time.
Note: The definition of TIME is based on the high-resolution TIME specification [HR-time -2] and differs from the TIME definition used in the Navigation-timing specification, which is measured in milliseconds from midnight on January 1, 1970 (UTC).
The text – the Resource Timing
An overview of the
PerformanceResourceTiming interface helps to downloadable resources for timing measurement. For example, resources can be powered from XMLHttpRequest objects, HTML elements HTML51 (such as iframe, IMG, scripts, objects, embedded and links with style sheet link types), and SVG elements SVG11.
PerformanceResourceTiming Resources
All by browsing program [WORKERS] [HTML] or work context available resources must be in the Performance Timeline contains PerformanceResourceTiming object, and not in violation of the same origin policy. From relevant application cache retrieve or local resources must also be in Performance including PerformanceResourceTiming object in the Timeline. PERFORMANCE-TIMELINE-2
Note: Future versions of the specification may need to include aborted requests or requests that do not return a response. See the issues for 12
Note: Developers should be aware of Issue 27: Same Origin policy and compliance with Non-domain access.
The following are special cases
Such as: If a resource fetch is aborted because it failed a fetch precondition (e.g. mixed content, CORS restriction, CSP policy, etc), then this resource will not be included as a PerformanceResourceTiming object in the Performance Timeline.
- If two urls of the same specification are treated as SRC attributes of two HTML IMG elements, the picture resource that gets the first HTML element contains the Performance Timeline object. Instead of repeatedly requesting a URL for the second HTML IMG element, the client might use a local download of the first element. In this case, only the first element has a Performance Timeline object for resource retrieval.
- If an HTML element of IMG SRC attribute is through script change, whether to obtain the original resource, or access to the new URL will be in the Performance Timeline contains PerformanceResourceTiming object.
- If the IFRAME is added to the HTML via a tag without specifying a SRC attribute, the client can load about:blank DOM for the HTML. The new IFRAME URL resource that can be retrieved by the client if the SRC property is subsequently changed dynamically via the script. In this case, only the new URL in the Performance of the Timeline contains PerformanceResourceTiming object.
- If the same XMLHttpRequest request twice, get twice the resources will be in the Performance Timeline contains PerformanceResourceTiming object. This is because the fetch asynchronous request for the second resource cannot reuse the downloaded asynchronous request for the first resource.
- If the page contains the IFRAME element, it is only when containing SRC attribute in the Performance Timeline contains PerformanceResourceTiming object. The IFRAME file requires that the child resources be included in the Performance Timeline of the IFRAME file, not in the Performance Timeline table of the parent document.
- If the HTML IMG element data: the source of the URI for [RFC2397], the resource was not in the Performance Timeline contains PerformanceResourceTiming object. By definition, its DATA: URI contains embedded data and does not need to be retrieved.
- If the resource acquisition due to network error (such as DNS, TCP and TLS) and suspended, then the resource acquisition in the Performance Timeline contains PerformanceResourceTiming object, And initialization of property values up to the point of failure (such as a TCP handshake) should report the DNS timestamp of the request, and so on.
- If for obtaining prerequisites (for example, mixed content, CORS, CSP strategy, etc.) failure led to the suspension of resource acquisition, then the resources not in Performance Timeline contains PerformanceResourceTiming object.
The PerformanceResourceTiming
One of the keys to this article
PerformanceResourceTiming interface in Performance Timeline display panel, and its extension PerformanceEntry interface has the following properties:
- Name: This property must return the parse URL of the requested resource. This property does not change if redirected to another URL.
- EntryType: The entryType property returns DOMString “resource”.
- StartTime: The startTime property returns a DOMHighResTimeStamp [hr-time -2] indicating the TIME before the user agent starts queuing for the resource. This property returns the value of redirectStart if there is HTTP redirection or similarity when retrieving a resource and all redirection or similarity is from the same source as the current document or through the Timing Allow Check algorithm. Otherwise, this property returns the value of fetchStart.
- Duration: This duration property returns a DOMHighResTimeStamp equal to the difference between responseEnd and startTime.
[Exposed=(Window)]
interface PerformanceResourceTiming : PerformanceEntry {
readonly attribute DOMString initiatorType;
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;
serializer = {inherit, attribute};
};
Copy the code
When obtained, the initiatorType attribute returns the following:
- If the initializer is Element, the localName value of Element [DOM] is returned.
- Return “CSS” if the originator is a CSS resource downloaded by url()[css-syntax-3] SYNTAX, such as @import URL () or background: url().
- If the originator is the XMLHttpRequest object [XHR], “XMLHttpRequest” is returned.
- When obtained, the redirectStart property returns the following:
-
If there is HTTP redirection or similarity when obtaining resources, and all redirection or similarity situations are passed by timing allow Check algorithm, returns the time when the client program is about to obtain the resources used to start the redirection.
-
Otherwise, return 0.
- When obtained, the redirectEnd property returns the following:
- Timing Allow Check Timing Allow Check Timing Allow Check Timing Allow Check Timing allow Check Timing allow Check Timing allow Check Timing allow Check Timing allow Check Timing allow Check Timing allow Check Timing allow Check Timing allow Check Timing allow Check Timing allow Check Timing allow Check Timing allow Check Timing allow Check Timing allow Check Timing allow Check Timing Allow Check Timing Allow Check Timing Allow Check Timing Allow Check Timing Allow Check Timing Allow Check Timing Allow Check Timing Allow Check Timing Allow Check Timing Allow Check
- Otherwise, return 0.
- When obtained, the fetchStart attribute must return the following:
- If there is an HTTP redirect or similar, return: the time before the client begins retrieving the final resource immediately after the redirect.
- In other cases, return: the time before the client immediately starts retrieving the resource.
- When obtained, the domainLookupStart property returns the following:
- FetchStart is returned if a persistent connection [RFC7230] is used or the resource is retrieved from an associated application cache or local resource.
- If the client contains domain information in the cache, return: Retrieves the start time from the client’s information cache in the corresponding domain.
- Timing allow Check Timing allow Check Timing allow Check Timing allow Check Timing allow Check Timing allow Check Timing allow Check Timing allow Check Timing allow Check Timing allow Check Timing allow Check Timing allow Check Timing allow Check Timing allow Check Timing allow Check Timing timing
- Otherwise, return 0.
- When obtained, the domainLookupEnd property returns the following:
- FetchStart is returned if a persistent connection [RFC7230] is used or the resource is retrieved from an associated application cache or local resource.
- If the client contains domain information in the cache, returns the time when the data retrieval from the client in the information cache of the corresponding domain ends.
- If the last unredirected acquisition of a resource passes Timing allow Check, the time immediately before the client completes the resource search under the domain name is returned.
- Otherwise, return 0.
- When obtained, the connectStart property returns as follows:
- FetchStart is returned if a persistent connection [RFC7230] is used or the resource is retrieved from an associated application cache or local resource.
- If the last unredirected acquisition of a resource passed the Timing Allow Check algorithm, returns the time before the client starts to connect to the server to retrieve the resource. If the transport connection fails and the client reopens the connection, the corresponding connectStart value for the new connection should be returned.
- Otherwise, return 0.
- When obtained, the connectEnd property returns the following information:
- FetchStart is returned if a persistent connection [RFC7230] is used or the resource is retrieved from an associated application cache or local resource.
- Return: the time when the client started to connect to the server to retrieve the resource (if the last unredirected resource was acquired by timing allow Check). The time returned must include the interval between establishing the transport connection, as well as other intervals, such as the SSL handshake and SOCKS authentication. If the transfer connection fails and the client reopens the connection, the corresponding connectEnd value for the new connection should be returned.
- Otherwise, return 0.
- The secureConnectionStart property is optional. When obtained, the property returns the following:
- FetchStart is returned if a persistent connection [RFC7230] is used or the resource is retrieved from an associated application cache or local resource.
- If secure transport is used and the last unredirected acquisition of the resource passed Timing allow Check, returns the time when the client program immediately begins the handshake process to ensure that the current connection is secure.
- Otherwise, return 0.
- When obtained, the requestStart attribute returns the following:
- If the last unredirected resource acquisition passed the Timing Allow Check algorithm, the time is returned before the client program starts requesting the resource from the server in the related application cache or from the local resource.
- If the transfer connection fails after sending the request, and the user agent reopens the connection and resends the request, the corresponding requestStart value for the new request must be returned.
- Otherwise, return 0.
Pay attention to
- This interface does not contain: send request completion properties, such as requestEnd. The completion of a request sent from the client does not always indicate the corresponding completion time in the network transfer, which makes the requestEnd attribute more useful.
- Due to the ENCAPSULATION of the HTTP layer, it can be expensive for some clients to determine the actual completion time for sending a request.
- When obtained, the responseStart property returns the following:
- Return: the time immediately after the client receives the first byte of the response from the relevant application cache, local resource, or server (this last resource fetch is non-redirected and is performed by timing Allow Check algorithm).
- Otherwise, return 0.
- When obtained, the responseEnd property returns the following:
- Return: The time after the last byte of the response is received by the client or before the transport connection is closed, whichever comes first. If the last unredirected acquisition of a resource passed the Timing Allow Check algorithm, the resource can be received from the associated application cache, local resource, or server.
- Otherwise, return 0.
This section ends with a list of various return values for the various properties of PerformanceEntry.
I have to say that the documentation is the specification.
And here have to dig a pit 🕳, timing allow check algorithm, follow-up study!
Performance Interface Extension
The client can choose the Performance Timeline [Performance – Timeline – 2] PerformanceResourceTiming object of limitation. This section expands the Performance interface, allow for more control PerformanceResourceTiming storage object.
Recommended minimum PerformanceResourceTiming object number is 150, the client can change, through setResourceTimingBufferSize method also can change this limit.
Each ECMAScript global environment has:
- Resource Timing Buffer size limit. The initial value should be 150 or larger.
- Resource Timing Buffer current size (timing of the resource of the current buffer size). The initial value is 0.
- Resource timing Buffer Full flag (The resource timing buffer is full), initially false.
- PerformanceEntry Buffer Stores PerformanceEntry objects. At first it was empty.
Note that buffering has the same meaning as PERFORMANCE item buffering defined in [performance-Timeline-2].
partial interface Performance {
void clearResourceTimings();
void setResourceTimingBufferSize(unsigned long maxSize);
attribute EventHandler onresourcetimingbufferfull;
};
Copy the code
The Performance object is defined in [hr-time -2].
ClearResourceTimings method
- Delete the performance entry all PerformanceResourceTiming object in the buffer.
- Sets the current size of the resource timing buffer to 0.
- Set the resource timing buffer full flag to false.
SetResourceTimingBufferSize method implementation process:
- Set the resource timing buffer size limit to the maxSize parameter. If maxSize parameters less than the current size of timing buffer resources, from the performance is not an entry in the buffer to delete any PerformanceResourceTiming object.
- Set the resource timing buffer full flag to false.
Onresourcetimingbufferfull attributes is resourcetimingbufferfull event event handler.
In the performance entry is added to the buffer, PerformanceResourceTiming items (new items), to make the following steps:
- If the current size of the resource timing buffer is smaller than the maximum size of the resource timing buffer, perform the following steps: a. Adds the new entry to the performance entry buffer. B. Increase the current size of the resource timing buffer.
- Also, if the resource timing buffer is full flag is false, run the following steps: a. A simple event called ResourceTimingBufferFull is fired on the document with the bubbles property initialized to true and no default action. B. Set the resource timing buffer full flag to true.
Cross-domain resources
Timing allow check mentioned above is explained here
Timing-allow-origin HTTP response header field used for communication is allowed to be seen, due to cross-domain restrictions the attribute value is 0. Header values are defined by the following ABNF [RFC5234] :
that would have been zero due to the cross-origin restrictions. The header’s value is represented by the following ABNF [RFC5234]:
Timing-allow-origin = 1 #Copy the code
The sender can generate multiple Timing-Allow-Origin header fields. The receiver can combine multiple timing-Allow-Origin header fields by appending each subsequent field value to the combined field values in sequence and separating them by commas.
Timing allow Check Algorithm, which checks whether the timing information of a resource can be shared in the current document, as follows:
- If the resource is from the same source, pass is returned.
- Return Pass if the timing-allow-Origin header value list contains a (case sensitive) match to the current document value or wildcard (” “).
- Otherwise, return FAIL.
The implementation process
Processing model
Principle is the core!
The figure below illustrates the from multiple access to resources when PerformanceResourceTiming interface definition of temporal properties. Underlined attributes may not be available. Clients can perform internal processing between times, which allows non-standard intervals between times.
For each resource contained in the Performance Timelime, perform the following steps:
- Create a new PerformanceResourceTiming object, and will provide DOMString entryType resource Settings.
- The current time is recorded in startTime before the client starts queuing the resource for retrieval.
- Record the initial initiator in initiatorType.
- Record the parse URL of the requested resource in name.
- Before the client starts the fetch process immediately, record the current time as fetchStart. Make the values of domainLookupStart, domainLookupEnd, connectStart, connectEnd, and fetchStart the same.
- If the client wants to reuse data from another existing or completed fetch from the current document, the remaining steps are aborted.
- If the retrieval of the resource is aborted for any reason, the remaining steps are aborted.
- If redirectStart, redirectEnd, domainLookupStart, domainLookupEnd, connectStart, and connectEnd are not allowed to be checked. RequestStart, responseStart, and secureConnectionStart are zero and jump to Step 17.
- Make the values of domainLookupStart, domainLookupEnd, connectStart, connectEnd, and fetchStart the same.
- If the resource is fetched from the relevant application cache or local resources, including the HTTP cache [RFC7234], go to Step 15.
- If you do not need to search for a domain, go to Step 13. Otherwise, record the time as domainLookupStart before the client immediately starts the domain name lookup.
- Record the domainLookupEnd time immediately after the domain name is successfully searched. The client may need to retry several times before doing this. If the domain lookup fails, the remaining steps are aborted.
- If persistent transport connections are used to obtain resources, set connectStart and connectEnd to the same value as domainLookupEnd. Otherwise, record the time as the time before connectStart first started the connection to the server, and record the time after connectEnd immediately established the connection to the server or agent. The browser may need to retry several times before this time. If the connection cannot be established, the remaining steps are aborted.
- If secureConnectionStart is supported, the client must set the secureConnectionStart property as follows: ① When secure transport is used, the client records the time before secureConnectionStart is used as a secure handshake. ② When secure transmission is not used, the client sets secureConnectionStart to 0.
- Record the current time as requestStart before the client immediately starts sending requests for resources.
- The user agent logs the time immediately after the first byte of the response is received as responseStart.
- Record the time responseEnd immediately after the last byte of the response is received. (1) If the client fails to send the request or receive the entire response and needs to reopen the connection, go to Step 13.
Example 3 When persistent connection [RFC7230] is enabled, the client can first attempt to re-send the request using an open connection, and the connection can be closed asynchronously. In this case, connectStart, connectEnd, and requestStart should represent the collected timing information for reopened connections.
- During the process, record the difference between responseEnd and startTime.
- RedirectStart and redirectEnd are set to 0 if the redirected resource is not from the same source, document, or timing allow Check is not adopted. Then, return to the new resource of Step 5. ② If the redirectStart value is not set, set it to the fetchStart value. ③ Set redirectEnd to responseEnd. (4) in all of the attributes set PerformanceResourceTiming object is 0, except tartTime, redirectStart redirectEnd, and initiatorType. ⑤ To query new resources, return to Step 5.
- Add PerformanceResourceTiming object
Boring time
Monotonic clock(time) literally means Monotonic time, but it actually refers to the amount of time that has elapsed since a certain point (such as after the system is booted up)
The value of the timing attribute must be monotonically increased to ensure that the timing attribute will not be offset by adjusting the system clock when obtaining resources. The difference between any two chronologically logged timing attributes must never be negative. For all resources, including subdocument resources, the browser must record the system clock at the beginning of the root document navigation and define subsequent timing properties based on a monotonic clock that measures the elapsed time since the navigation began.
other
Privacy and Security
PerformanceResourceTiming interface to the timing information of public resources to have any request to the resource web pages or workers. In order to restrict access to PerformanceResourceTiming interface, by default will enforce the same original strategy, and put some attribute is set to zero, as described in the cross-domain resources. A resource provider can explicitly Allow the collection of all Timing information for a resource by adding a timing-allow-Origin HTTP response header that specifies the domain to Allow access to Timing information.
Statistical fingerprinting is a privacy issue in which a malicious website may determine whether a user has visited a third party website by measuring the timing of cache hits and resource losses in the third party website. Although PerformanceResourceTiming interface provides the timing information in the document resources, but the cross-domain restrictions prevent this privacy than today use resources to measure the load event sequence to determine cache hits and misses.
Though the PerformanceResourceTiming interface gives timing information for resources in a document, the cross-origin restrictions 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 and quotations
- Thank you
- reference
summary
I have to say that the official document is really rigorous, in the process of translation, but also to their ability to write documents is a kind of improvement!
In addition, the following indicators in the development of any website to try to pay attention to, develop good habits:
DNS query duration: domainLookupEnd - domainLookupStart TCP connection duration: connectEnd - connectStart Request request duration: ResponseEnd - responseStart Dom tree parsing time: domComplete - domInteractive White screen time: NavigationStart domReady: domContentLoadedEventEnd - navigationStart onload: loadEventEnd - navigationStartCopy the code
Expectations: More front-end monitoring (not limited to performance monitoring) in the future!