After the project goes online, it is usually buried in data monitoring, abnormal monitoring and performance monitoring. This paper mainly talks about front-end performance monitoring. How to monitor performance?

Front-end performance monitoring usually detects the load time of certain aspects, and determines the performance of certain aspects of the project by the length of the load time obtained. Let’s take a look at how page loading works:

Page load

There are two ways to load a page. One is to dynamically obtain the interface data through javascript after loading the resource file, and then the data is returned to render content, which is the project page loading mode with the separation of the front and back ends. The other is server rendering, isomorphic straight front page, this way relative to the first way page loading speed is much faster, performance is relatively better. However, most current projects are separated from the front and back ends, and this article focuses on this approach.

  1. Type in the url and press Enter
  2. Cache resolution: If the browser’s local cache has resources from the cache
  3. Domain name resolution:DNSResolve: Resolves the domain name intoIPIf it exists in the cache, fetch it directly from the cacheIP, do not do domain name resolution
  4. Send a request: Sends a request to the server
  5. TCPConnection, three-way handshake: Establishes a browser-server connection
  6. The server receives a request: The server responds to the request
  7. The data transfer
  8. The browser takes the data and parses ithtmlFile, buildDOMThe tree,CSSOMThe tree,jsLoading files can block page rendering
  9. The initialhtmlEmitted when fully loaded and parsedDOMContentLoadedThe event
  10. CSSOMTrees andDOMThe generation of the tree will begin after the tree is builtRenderThe tree, draw
  11. In the generatedRenderTree process, the browser will start callingGPUDraw, compose layers, and display content on the screen
  12. No file transfer, four waves of the hand,TCPConnection is broken

The above is the basic process of page loading, did not expand, if you want to expand, ten articles can not finish, in this paper only need to clear about the whole process, later arrange the system to sort out the content of the whole process, do text output.

The whole process of page loading is mainly divided into white screen, redirection, DNS query, TCP connection, HTTP request, DOM parsing, DOMready, onload, etc. These are the main aspects of front-end performance monitoring. We need to monitor these aspects of data, do data analysis, and further front-end performance optimization. For example, how to speed up the first screen load time, reduce HTTP request time and so on.

The Chrome Developer Tools performance panel can also be used to monitor performance.

performance

Performance is an API used to monitor front-end performance. You can obtain performance related information on the current page.

Let’s take a look at some information obtained through the API window.performance on the homepage of Tmall:

window.performance
memory
navigation
timeOrigin
timing
onresourcetimingbufferfull

performance.memory

A non-standard extension added to Chrome, the memory property provides MemoryInfo, an object that can retrieve basic memory usage

performance.memory = {
  jsHeapSizeLimit, // Memory size limit, in bytes B
  totalJSHeapSize, // The size of available memory, in bytes B
  usedJSHeapSize   // The size of memory occupied by the JS object, in bytes B
}
Copy the code

If usedJSHeapSize is greater than totalJSHeapSize, memory leaks will occur, so it cannot be greater than totalJSHeapSize.

performance.navigation

Returns PerformanceNavigation object, which provides information about the operation that occurred during the specified time period, including whether the page was loaded or refreshed, how much redirection occurred, and so on.

performance.navigation = {
  redirectCount: xxx,
  type: xxx
}
Copy the code

PerformanceNavigation object has two properties, redirectCount and Type.

performance.navigation.redirectCount

Read-only: indicates the number of redirects before reaching the page. However, this interface is restricted by the same-origin policy and can only detect same-origin redirects.

performance.navigation.type

Read-only property with four return values: 0,1,2,225:

  • 0: indicates that the current page is performed by clicking links, bookmarking and form submission, or by scripting, or inurlDirectly enter the address, equivalent to a constantperformance.navigation.TYPE_NAVIGATE
  • 1: click refresh button or passA Location. Reload ()Method displays a page equivalent to a constantperformance.navigation.TYPE_RELOAD
  • 2: indicates that the page is accessed through history and forward and backward, which is equivalent to a constantperformance.navigation.TYPE_BACK_FORWARD
  • 225: represents any other loading method, equivalent to a constantperformance.navigation.TYPE_RESERVED

performance.timeOrigin

Returns a high-precision timestamp of the time when the performance measurement began.

performance.onresourcetimingbufferfull

A callback EventTarget that is called when the ResourceTimingBufferFull event is triggered.

performance.timing

The PerformanceTiming object is returned, which contains various browser performance related data and provides the time taken by the browser to process each stage of the page. The overall structure can be seen in the following figure:

PerformanceTiming
Unix

navigationStart

Returns the closing of the previous page of the current browser window, and the timestamp when an Unload event occurred. If there is no previous page, it equals the fetchStart attribute.

unloadEventStart

Returns the timestamp of the previous page’s Unload event when it occurred if the previous page is codomain with the current page. If there is no previous page or the previous page is not in the same domain name, 0 is returned

unloadEventStart

Corresponding to unloadEventStart, returns the timestamp when the callback function bound by the Unload event on the previous page has finished executing. If there is no previous page or the previous page is not in the same domain name, 0 is returned

redirectStart

Returns the timestamp when the first HTTP redirect occurred. There is a jump and it is a redirection within the same domain, otherwise the return value is 0

redirectEnd

Returns the timestamp when the last HTTP redirect was completed. There is a jump and it is a redirection within the same domain, otherwise the return value is 0

fetchStart

Returns the timestamp when the browser is ready to grab the document using an HTTP request, before checking the local cache

domainLookupStart

FetchStart returns the timestamp from which the DNS domain name query started, equal to the value of fetchStart if the local cache was used (that is, the IP was fetched from the cache without DNS query) or if the persistent connection was used

domainLookupEnd

FetchStart returns the timestamp when the DNS query was completed, equal to the fetchStart value if the local cache was used or if the persistent connection was used

connectStart

Returns the timestamp when the HTTP (TCP) connection was started, equal to the fetchStart value if the connection is persistent. If an error occurs at the transport layer and the connection is re-established, the timestamp shown here is the start of the newly established connection

connectEnd

Return the timestamp when the HTTP (TCP) connection was established, completing the quad handshake, or equal to the fetchStart value if the connection is persistent. If an error occurs at the transport layer and the connection is re-established, the timestamp for the completion of the newly established connection is displayed here. Connection establishment refers to the completion of all handshake and authentication processes

secureConnectionStart

Returns the timestamp when the HTTPS connection started, or 0 if it is not a secure connection

requestStart

Returns the timestamp from which the HTTP request was made to read the real document (completing the connection), including reading from the cache locally. If the connection is reconnected incorrectly, the timestamp of the newly established connection is also displayed here

responseStart

Returns the timestamp when the HTTP began receiving the response (the first byte was retrieved), including reading from the local cache

responseEnd

Returns a timestamp that the HTTP response has been fully received (fetched to the last byte), including reading from the local cache

domLoading

Returns the timestamp when parsing the rendering DOM tree begins, document. readyState becomes loaded, and the readyStatechange event is thrown

domInteractive

Return the timestamp when parsing the DOM tree is complete, document. readyState changes to interactive, and a readyStatechange related event is thrown. This is just the DOM tree parsing done, not the loading of resources within the page

domContentLoadedEventStart

Returns the timestamp of the start of resource loading in the web page after DOM parsing is complete. All scripts that need to be executed start being parsed. Occurs before the DOMContentLoaded event is thrown

domContentLoadedEventEnd

Returns the timestamp when the page resources are loaded after DOM parsing is complete. For example, the JS script is loaded and executed, regardless of the execution order. The DOMContentLoaded event has also been completed

domComplete

Returns a timestamp when DOM parsing is complete and the resource is ready. Document.readyState becomes complete and a readyStatechange related event is thrown

loadEventStart

Returns the timestamp when the LOAD event is sent to the document and the load callback function starts executing. If no load event is bound, the return value is 0

loadEventEnd

Returns the timestamp when the callback function of the load event completes execution. If no load event is bound, the return value is 0

The above attributes have been explained, and there are many things you can do with the above data to help you with performance monitoring:

  • Page load completion time: represents the time the user waits for the page to be available
let performance = window.performance;
let t = performance.timing;
let time = t.loadEventEnd - t.navigationStart;
Copy the code
  • Time to parse the DOM tree structure: judgmentDOMTree nesting
let performance = window.performance;
let t = performance.timing;
let time = t.domComplete - t.responseEnd;
Copy the code
  • Redirection time
let performance = window.performance;
let t = performance.timing;
let time = t.redirectEnd - t.redirectStart;
Copy the code
  • DNSQuery time: Preloading and caching can be used to reduce the query time
let performance = window.performance;
let t = performance.timing;
let time = t.domainLookupEnd - t.domainLookupStart;
Copy the code
  • White screen time: the time to read the first byte of a page
let performance = window.performance;
let t = performance.timing;
let time = t.responseStart - t.navigationStart;
Copy the code
  • The time when the content is finished loading
let performance = window.performance;
let t = performance.timing;
let time = t.responseEnd - t.requestStart;
Copy the code
  • performonloadThe time of the callback function
let performance = window.performance;
let t = performance.timing;
let time = t.loadEventEnd - t.loadEventStart;
Copy the code
  • DNSCache time
let performance = window.performance;
let t = performance.timing;
let time = t.domainLookupStart - t.fetchStart;
Copy the code
  • The time to uninstall the page
let performance = window.performance;
let t = performance.timing;
let time = t.unloadEventEnd - t.unloadEventStart;
Copy the code
  • TCPThe time at which the connection is established to complete the handshake
let performance = window.performance;
let t = performance.timing;
let time = t.connectEnd - t.connectStart;
Copy the code

We can calculate the time consuming of each stage of the page loading process, judge the performance of a stage according to the time, and then do further optimization. This is an important step in performance optimization, and we need to identify specific phases that are taking too long and apply the appropriate measures.

Performance also provides some methods, so let’s take a look at some common ones:

Custom statistical methods

performance.mark()

Create a DOMHighResTimeStamp and store it in the resource cache data. It can be obtained from an interface such as performance.getentries (). The simple understanding is that you can mark, that is, “dot.”

performance.mark(name);
Copy the code

performance.clearMarks()

Used to clear tokens. If no argument is added, all tokens are cleared.

performance.clearMarks(name); // Clear the specified flag
performance.clearMarks(); // Clear all flags
Copy the code

performance.measure()

Calculate the time between two Marks and create a DOMHighResTimeStamp, which is stored in the resource cache data and can be obtained through an interface such as performance.getentries ().

performance.measure(name, startMark, endMark);
Copy the code

performance.clearMeasures

Example Remove all resource data whose entryType is measure from the cache.

performance.clearMeasures(name); // Clear the specified record interval data
performance.clearMeasures(); // Clear all record interval data
Copy the code

The above four apis allow you to customize statistics such as the execution time of a function.

It is also useful in Vue. To track component performance, the global configuration API in ve2.X has this method:

Vue.config.performance = false;
Copy the code

Set to true to enable performance tracking for component initialization, compilation, rendering, and patching in the browser developer’s Performance/timeline panel. Only works in development mode and on browsers that support the Performance. Mark API. You can use Vue Performance Devtool to check the loading status of each component:

if(process.env.NODE_ENV ! = ='production') {
  Vue.config.performance = true;
}
Copy the code

Vue
performance.mark
performance.measure

// vue/src/core/util/perf.js
import { inBrowser } from './env'

export let mark
export let measure

if(process.env.NODE_ENV ! = ='production') { // Environment check the development environment to execute the following program
  const perf = inBrowser && window.performance // Browser environment
  /* istanbul ignore if */
  if (
    perf &&
    perf.mark &&
    perf.measure &&
    perf.clearMarks &&
    perf.clearMeasures
  ) {
    mark = tag= > perf.mark(tag) // Add a tag to the tag
    measure = (name, startTag, endTag) = > {
      perf.measure(name, startTag, endTag) // Calculate the time between marks
      perf.clearMarks(startTag) // Clear the startTag
      perf.clearMarks(endTag) // Clear the endTag
      // Perf. clearMeasures(name) // Clear the specified record interval data}}}Copy the code

As you can see from the above code, you encapsulate performance.mark() and performance.measure() using the mark and measure functions. Let’s take a look at how to use the source code:

// vue/src/core/instance/init.js
import { mark, measure } from '.. /util/perf'
export function initMixin (Vue: Class<Component>) {
  Vue.prototype._init = function (options? : Object) {
    vm._uid = uid++
    let startTag, endTag
    /* istanbul ignore if */
    if(process.env.NODE_ENV ! = ='production' && config.performance && mark) {
      startTag = `vue-perf-start:${vm._uid}`
      endTag = `vue-perf-end:${vm._uid}`
      mark(startTag) // Start the tag
    }
    / /... Intermediate code omission
    // a series of initialization functions
    // initLifecycle(vm)
    / /...
    /* istanbul ignore if */
    if(process.env.NODE_ENV ! = ='production' && config.performance && mark) {
      vm._name = formatComponentName(vm, false)
      mark(endTag) // End tag
      measure(`vue ${vm._name} init`, startTag, endTag) // Calculate the time between marks}}}Copy the code

The above is the related program of Vue initialization implementation. The above marking is to track the performance of component initialization, that is, mark two marks at the beginning and end of the initialization code respectively by using the mark function, and then calculate the performance of these two marks through the measure function. Performance tracking is also done in compilation, rendering and patching for those who are interested.

Above is the application of Performance in Vue. When I first read the source code of Vue, I saw this piece is not very clear. It does not affect the overall reading, it does not matter. Let’s look at a simpler example to understand it better:

performance.mark('markStart'); For (let I = 0; i < 10; i++) { console.log(i); } performance.mark('markEnd'); // Mark an end point performance.measure('measureVal', 'markStart', 'markEnd'); let measures = performance.getEntriesByName('measureVal'); let measure = measures[0] console.log('milliseconds: ', measure.duartion); // clear the mark performance.clearmarks (); performance.clearMeasures();Copy the code

The API provided above calculates the execution time of the for loop. These apis are frequently used in performance monitoring applications.

Method for obtaining performance resources

performance.getEntries

Get the time data for all resource requests. This function returns an array of objects sorted by startTime:

As you can see from the above, the returns are all related to the resource page load. Many of the attributes are the same as performance. Timing and will not be explained here. Here are a few other important attributes to comb through:

  • name: resource name, which is the absolute path to the resource or a custom name by calling the MARK method (e.gentryTypeforresource, name indicates the path of the resource.
  • duration, aDOMHighResTimeStampObject to get how long the resource is consumed.
  • startTime, aDOMHighResTimeStampObject at which the resource was first acquired.
  • entryType:
value Object of this type describe
mark PerformanceMark throughmark()Method added to an array
measure PerformanceMeasure throughmeasure()Method added to an array
paint PerformancePaintTiming A value offirst-paintFirst drawing,first-contentful-paintFirst content drawing
resource PerformanceResourceTiming Load time of all resources, most useful
navigation PerformanceNavigationTiming Now in addition tochromeandOperaExternal are not supported, navigation related information
frame PerformanceFrameTiming None of the current browsers support it
  • initiatorTypeInitializes the resource type of the resource:
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 throughcssStyle loaded resources such asbackgroundtheurlHow to load resources
a XMLHttpRequest object xmlhttprequest/fetch throughxhrLoaded resources
a PerformanceNavigationTiming object navigation When the object isPerformanceNavigationTimingWhen to return to

performance.getEntriesByName

Retrieves a set of resource data that has been loaded on the current page with parameters name, type. The value of name corresponds to the name field in resource data, and the value of type corresponds to the entryType field in resource data.

let entries = window.performance.getEntriesByName(name, type);
Copy the code

performance.getEntriesByType

Gets a set of resource data that has been loaded for the current page based on the type parameter. The type value corresponds to the entryType field in the resource data

let entries = window.performance.getEntriesByType(type);
Copy the code

GetEntriesByName and getEntriesByType can be used to obtain resource data of a certain type by specifying parameters. In this way, resource data can be classified and counted to obtain various types of data.

This is the main content of Performance. You can use this API to do a lot of things about performance monitoring. You need to make appropriate solutions according to your specific scenarios. If you are familiar with Chrome developer tools, you can also use the Performance panel to perform performance monitoring. Why do you also provide API to perform performance monitoring?

conclusion

If the article is not correct, you are welcome to correct, also hope to see the article students have harvest, grow together!

— This article was first published on personal public account —