In the last article, we talked about Performance monitoring in Chrome, but most of the time, we want to collect data from the client actively, and the browser debugging tool is not enough.

The window.performance object is recommended.

What is Performance

Allows Web pages to access certain functions to measure the performance of Web pages and Web applications, including Navigation Timing API and high-resolution temporal data.

Source: the MDN

Performance objects are essentially performance monitoring objects, with almost all of the performance parameter monitoring required by the common front-end built in.

Note: All apis for the Performance object are read-only.

Such as:

  • To a specific time from the time you enter the address
  • Parsing the DOM tree takes time
  • Bad time
  • Domready time
  • Onload time
  • Redirection Time
  • Request Request Time

There are:

  • All object statistics for the current page
  • User behavior information

Ii. Compatibility with Performance

Performance’s monitor front end performance has been rolled out to make almost all browsers comfortable. (except Internet Explorer 9 below) and all browsers are doing their best to be backward compatible.

Don’t be blindly optimistic:

  1. The return result of the performance built-in method varies with kernel browsers. For example, when obtaining a list of all HTTP requests, Firefox returns failed and successful requests, while Chrome returns only successful requests.

  2. Many of performance’s built-in apis are browser-based implementations and therefore limited to mobile or client applications. (getEntries(), etc.)

Performance API

There are many apis for Performance, but a few are particularly useful.

1. Performance. Now () method

The performance. Now () returns the performance. NavigationStart to the current number of milliseconds. Performance. NavigationStart is below will be introduced to the measurement point can be said to be the browser to access the first time.

Two points worth noting:

  • The initial measurement point is the moment when the browser accesses the initial measurement point, or is understood as the moment when you enter the URL in the address bar and press Enter.
  • The return value is the number of milliseconds, but with the exact number of decimal places.

Test for loop execution time (ms) with performing.now ()

    var st = performance.now();
    for (var o = 0; o < 10000; o ++)  console.log(o)
    var end = performance.now();

    console.log(`fortime${end - st}`); // forTime is 1155.9950000373647Copy the code

2. Performance. Navigation attributes

Performance. Navigation records user behavior information and has only two properties.

console.log(performance.navigation);
// PerformanceNavigation {type: 1, redirectCount: 0}
Copy the code
  • Type: indicates the loading source of the web page. There are four possible cases

    • 0: web pages are loaded by clicking links, entering address bars, submitting forms, and script operations, which is equivalent to a constant
    • 1: The page is loaded via the reload button or the location.reload() method
    • 2: The page is loaded through the “forward” or “back” buttons
    • 255: Loads from any other source
  • RedirectCount: indicates the number of redirects to the current page.

3. Performance. Timing object

As one of the most important properties of Performance, Timing contains almost all time nodes. (1) attached

The common time point of collation is calculated as follows: Copy and paste directly.

window.onload = function() {
  var timing  = performance.timing;
  console.log('New page preparation time:' + timing.fetchStart - timing.navigationStart);
  console.log('Redirect Redirect time:' + timing.redirectEnd  - timing.redirectStart);
  console.log('Appcache time: ' + timing.domainLookupStart  - timing.fetchStart);
  console.log('Document Time before unload:' + timing.unloadEventEnd - timing.unloadEventStart);
  console.log('DNS query time: ' + timing.domainLookupEnd - timing.domainLookupStart);
  console.log('TCP connection time: ' + timing.connectEnd - timing.connectStart);
  console.log('Request Request time:' + timing.responseEnd - timing.requestStart);
  console.log('White screen Time:' + timing.responseStart - timing.navigationStart);
  console.log('Request completed until DOM load:' + timing.domInteractive - timing.responseEnd);
  console.log('Dom tree interpretation time:' + timing.domComplete - timing.domInteractive);
  console.log('Total time from start to load:' + timing.loadEventEnd - timing.navigationStart);
}
Copy the code

One important thing to note: the main reason for executing in window.onload is to get most of the Timing attributes after rendering, and can also be executed in a timer.

4. Performance. Mark (markName) method

Marked at custom time points, corresponding to peformance.clearmarks (markName)/performance.clearmarks (); The actual compatibility is not ideal… (Or maybe I’m using it wrong)

5. Performance. The memory properties

Performance. Memory Displays the current memory usage.

console.log(performance.memory);
/* MemoryInfo {
  totalJSHeapSize: 11735319,
  usedJSHeapSize: 9259919,
  jsHeapSizeLimit: 2197815296
} */
Copy the code
  • UsedJSHeapSize indicates the memory occupied by JS objects (including objects in the V8 engine)
  • TotalJSHeapSize Specifies the available memory
  • JsHeapSizeLimit: Indicates the memory size limit

In general, usedJSHeapSize cannot be greater than totalJSHeapSize; if it is, there may be a memory leak.

6. The performance. However, () method

When the browser fetches a web page, it makes an HTTP request for each object in the page (script files, style sheets, image files, and so on). The Performance. GetEntries method returns an array of Performanceentries, time statistics for those requests, and as many members as there are requests.

Name: resource name, which is the absolute path of the resource or customized by calling mark method startTime: startTime duration: load time entryType: resource type. Object structures in arrays vary depending on the entryType. See initiatorType below: Who initiated the request, see below

EntryType value:

value Object of this type describe
mark PerformanceMark Objects added to the array by the mark() method
measure PerformanceMeasure Objects added to the array through the measure() method
paint PerformancePaintTiming Values are first-paint’ first paint’, ‘first-contentful-paint’ first content paint.
resource PerformanceResourceTiming Load time of all resources, most useful
navigation PerformanceNavigationTiming Navigation information is not currently supported except for Chrome and Opera
frame PerformanceFrameTiming None of the current browsers support it

Also see: MDN

InitiatorType value:

A object value describe
a Element link/script/img/iframeEtc. A resource loaded as a label whose value is the lower case of the node name
a CSS resourc css Resources loaded with CSS styles, such as background URLS
a XMLHttpRequest object xmlhttprequest/fetch Resources loaded through XHR
a PerformanceNavigationTiming object navigation When the object is PerformanceNavigationTiming returns

2. The first item of the array returned by this method is the HTML page information

How to convey the message of Performance

  1. sendBeaconmethods
  2. dynamic<img>The label
  3. web wroker

That’s all for later…


Reference:

  1. Developer.mozilla.org/zh-CN/docs/…
  2. Developer.mozilla.org/en-US/docs/…
  3. Javascript.ruanyifeng.com/bom/perform…
  4. www.cnblogs.com/bldxh/p/685…

Add 1:

The property name meaning
navigationStart The Unix timestamp at which an Unload event occurs when the previous page of the browser window closes is the first measured time point
unloadEventStart Returns the Unix timestamp at the time of the unload event for the previous page when the previous page belongs to the same domain name as the current page
unloadEventEnd Returns the Unix timestamp at the end of the callback function of the unload event for the previous page when the previous page belongs to the same domain name as the current page
redirectStart Returns the Unix timestamp at the start of the first HTTP jump
redirectEnd Returns the Unix timestamp at the end of the last HTTP jump
fetchStart Returns the Unix timestamp when the browser is ready to use HTTP requests to read resources such as documents, before the web page queries the local cache
domainLookupStart Returns the Unix timestamp at the beginning of the domain name query. If persistent connections are used, or the information is fetched from a local cache, the return value is the same as the value of the fetchStart attribute
domainLookupEnd Returns the Unix millisecond timestamp at the end of the domain name query. If persistent connections are used, or the information is fetched from a local cache, the return value is the same as the value of the fetchStart attribute
connectStart Returns the Unix millisecond timestamp when the HTTP request began to be sent to the server. If persistent Connection is used, the return value is equal to the value of the fetchStart attribute
connectEnd Returns the Unix millisecond timestamp when the connection between the browser and the server was established. If a persistent connection is established, the return value is the same as the value of the fetchStart attribute. Connection establishment refers to the completion of all handshake and authentication processes
secureConnectionStart Returns the Unix millisecond timestamp when the browser and server began the handshake for the secure link. If the current page does not require a secure connection, 0 is returned
requestStart Returns the Unix millisecond timestamp when the browser makes an HTTP request to the server (or when it starts reading the local cache)
responseStart Returns the Unix millisecond timestamp when the browser receives the first byte from the server (or reads it from the local cache)
responseEnd Returns the Unix millisecond timestamp when the browser received (or read from the local cache) the last byte from the server (or closed if the HTTP connection has been closed before)
domLoading Returns the Unix millisecond timestamp when the DOM structure of the current web page starts parsing (that is, when the document. readyState property becomes “loading” and the corresponding readyStatechange event is triggered)
domInteractive Returns the Unix millisecond timestamp when the DOM structure of the current web page ends parsing and the embedded resource starts loading (that is, when the Document.readyState property changes to “interactive” and the corresponding readyStatechange event is triggered)
domContentLoadedEventStart Returns the Unix millisecond timestamp for the current web page when the DOMContentLoaded event occurs (that is, when the DOM structure is parsed and all scripts start running)
domContentLoadedEventEnd Returns the Unix millisecond timestamp when all scripts that need to be executed on the current page are completed
domComplete Returns the Unix millisecond timestamp when the DOM structure of the current web page was generated (that is, when the Document.readyState property became “complete” and the corresponding readyStatechange event occurred)
loadEventStart Returns the Unix millisecond timestamp at the start of the callback function for the current web page load event. If the event has not already occurred, return 0
loadEventEnd Returns the Unix millisecond timestamp at the end of the run of the callback function for the current page load event. If the event has not already occurred, return 0