An overview of the

Daily development tasks, for performance optimization more or less will come into contact with some content, may also refer to yahoo 35 catch-22 related performance optimization, but the specific optimization results and the actual page speed, how do we look at it? And how can we use existing tools to locate and solve performance problems? That is, today I am going to introduce the topic of “Performance”. The topic is more about tools, mainly from the following four aspects.

  • Using the Chrome Perormance tool: This section describes how to use the tools provided by the browser to locate the mance
  • Performance Api monitoring web Performance: How to do your own Performance data extraction
  • Existing detection tools: Introduction to three-party performance detection tools
  • Performance Tool demo: Use Performance with a small example

Use Chrome Performance

Performance in Chrome can be seen in the figure above, which is divided into several sections

Controls Panel

Enable recording, disable recording, and configure the content to be recorded during recording.

Operation is mainly divided into two areas, operation 1 from left to right is “Record/Stop”, “Reload” and “Clear”,

  • “Record/Stop” : generally used to Record the performance change data of the page interaction process, select any process you want to test, click “Record”, and at the end of the measurement, click “Stop”, then Chrome will automatically parse the data captured during this period of time, and generate a report.
  • “Reload” : Generally used to record performance changes on the first screen, it automatically refreshes the entire page and starts recording performance.
  • “Clear” : Clears performance report data

Operation area 2 allows you to select the report display content, including Screenshots, Memory and Web Vitals from left to right

  • Screenshots: When opened, you can see Screenshots in the overview area
  • Memory: Enables Memory monitoring
  • WebVitals

Overview Panel (Overview)

Primarily an overview of the behavior of the page presentation, the area consists of three graphical records.

  • FPS (Frames Per Second) : The taller the green column, the higher the FPS value. The small red block at the top of the FPS chart indicates long frames, which could be stuck.

  • CPU Resources: This area chart shows which events are consuming CPU Resources.
  • NET: Each bar of a different color represents a resource.

    • The longer the bar, the longer it takes to get the resource.
  • The light-colored part of each bar represents the wait time (the time it takes for the resource request to be sent until the first response byte is received) and the dark part represents the file transfer time (from the time the first byte is received until the resource is fully downloaded)

  • Blue represents HTML files, yellow represents Script files, purple represents Stylesheets files, green represents Media files, and gray represents other resources.

Flame Chart

  • Flame Chart: Visualizes the LOG of CPU stack information.

    • Analyze box selection areas from different perspectives. For example: Network, Frames, Interactions, Main, etc

    • On the flame panel you might see three vertical lines, the blue line representing the DOMContentLoaded event, the green line representing the time to first paint, and the red line representing the Load event.

In fact, we need to focus on Main here, because it is a monitoring of the Main thread. After clicking this button, we can see the stack time of some tasks in the current thread. We need to focus on the tasks marked red (i.e., those with high time).

Detail information

When a specific event is selected, this panel displays more details about the event. If no event is selected, this panel displays some information about the currently selected time period. The detail panel supports analysis down to the millisecond level

  • Summary panel: Summarizes the total browser loading time from a macro level, mainly recording the name, occupancy time, color information of each stage. In general, there are two areas to focus on: the yellow area, which represents script execution time, and the purple render time.

    • Color: blue; English: Loading; Meaning: Load

    • Color: yellow; English: Scripting; Meaning: Script

    • Color: purple; English: Rendering; Meaning: Render

    • Color: green; English: Painting; Meaning: Draw

    • Color: dark grey; English: Other; Meaning: Other

    • Color: light grey; English: Idle; Meaning: Idle

  • Bottom-up panel: There are three columns of data in the bottom-up

    • Self Time: indicates the Time consumed by the task itself.
    • Total Time: Represents the Total Time consumed by this task and its invoked dependent subtasks.
    • Activity: specific activities, part with a Source Map link, you can directly locate the specific Source code to spend time, convenient for us to locate and optimize. The Activity also has its own color, which corresponds to the color in the Summary. You can quickly determine whether it’s script execution, loading, or rendering by color.

  • Call-tree panel: Bottom-up similar events bubble and Call Tree similar events are captured. A top-down Call-Tree is more in line with our normal human thinking and allows for a more intuitive analysis of how the browser builds a page to the millisecond
  • Event-log panel: Shows the time of events in loading, javascripting, rendering, painting, etc. It also provides a filter input box and a button for quick filtering. It is not used in common optimization levels.

The Performance Api monitors web page Performance

In addition to the Performance test and debugging tools provided by browsers, the W3C also defines a set of Performance standards. Based on the standards, various browser vendors provide a series of basic apis for monitoring network Performance. These apis can detect the white screen time, the first screen time, and the time nodes that users can operate. Total page download time, DNS query time, TCP connection time, etc. We can use this to build a simple Performance monitoring tool, of course, the monitoring system includes data collection -> data storage -> cleaning -> monitoring several processes, but for now we briefly use the Performance Api to consider only the collection phase.

Capabilities provided

  1. Attribute article

All performance Api&property files are mounted under the Performance properties window. You can see a list of properties currently provided. For details on each property, refer to the aiP explanation online.

As shown in the figure above, Performance contains three objects: Memory, navigation, and Timing

  • Memory: Relates to memory, which provides a description of memory usage. We can use this property to subscribe to page memory changes

    • JsHeapSizeLimit: Limit of heap memory size
    • TotalJSHeapSize: Total heap memory size
    • UsedJSHeapSize: used heap memory size
  • Navigation: indicates the source of the page, how to jump to the page, the object has 2 property values

    • RedirectCount: Records the number of redirects, if any, by which the page was redirected. Default: 0
    • Type: indicates the page opening mode. The default value is 0. 0: indicates that the page is normally displayed (not refreshed or redirected), 1: indicates that the page is refreshed using window.location.reload, 2: indicates that the page is displayed using the forward and back buttons of the browser, 255: indicates that the page is displayed using the forward and back buttons of the browser. Means not enter the page in the above way”
  • Timing: Provides high-precision measurement of a series of key time points in the page loading process, including network, parsing, loading and a series of time data, we monitor the performance of the page based on this property. To facilitate understanding, I found a picture from the Internet to explain the meaning of the key nodes.

  • NavigationStart: Timestamp at the end of a page uninstallation. If there is no previous page, this value will be the same as fetchStart
  • RedirectStart: The timestamp at which the first HTTP redirect started, returning 0 if there was no redirect or if it was redirected to a different source
  • RedirectEnd: Timestamp when the last HTTP redirect is complete. This value is also returned to 0 if there is no redirect, or if the redirect is to a different source
  • FetchStart: The time when the browser is ready to fetch a document using an HTTP request (before checking the local cache).
  • DomainLookupStart: time when DNS domain name query starts. If local cache or persistent links are used, this value is the same as the fetchStart value
  • DomainLookupEnd: time when the DNS domain name query is complete. If local caching or persistent links are used, this value is the same as the fetchStart value
  • ConnectStart: The time when HTTP starts to establish a connection. This value is the same as fetchStart in the case of persistent links. If an error occurs at the transport layer and the connection needs to be re-established, the new link start time is displayed here
  • SecureConnectionStart: indicates the start time of the HTTPS connection. If the HTTPS connection is not secure, the value is 0
  • ConnectEnd: indicates the time when the HTTP connection is established (the handshake is completed). In the case of persistent links, this value is the same as the fetchStart value, showing the completion time of the newly established link if an error occurs at the transport layer and the connection needs to be re-established
  • RequestStart: the time when an HTTP request starts to read the actual document, including from the local cache, or when a link error reconnects
  • ResponseStart: The time at which the response is received (when the first byte is retrieved). This includes reading from the cache locally
  • ResponseEnd: the time when the HTTP response has been fully received (the last byte was retrieved). This includes reading from the cache locally
  • UnloadEventStart: The time stamp of the unload for the previous page (same as the current page), 0 if there is no previous page or the previous page is in a different domain
  • UnloadEventEnd: Corresponding to unloadEventStart, returns the timestamp when the previous page’s unload event bound callback function has finished executing.
  • DomLoading: The time to start parsing and rendering the DOM tree
  • DomInteractive: time to finish parsing the DOM tree (only DOM tree parsing is complete, but no web page resources are loaded)
  • DomContentLoadedEventStart: after DOM parsing is complete, the starting time of the web resources in loading
  • DomContentLoadedEventEnd: The time after DOM parsing is complete, the load of resources in the web page is complete
  • DomComplete: The time when the DOM tree is parsed and the resource is ready. Document.readyState becomes complete and a readyStatechange related event is thrown
  • LoadEventStart: Load the event to send to the document. This is the time when the load callback starts executing, or 0 if no LOAD event is bound
  • LoadEventEnd: The time when the callback function of the load event completes execution. This value is 0 if no load event is bound
  1. Methods paper

Performance provides some, as shown in the screenshot above. I’ll focus on the now() and getEntries() methods. Other online information is also more and more complete, you can refer to juejin.cn/post/684490…

  • The NOW method: provides relatively high precision time calculation mainly has the following two characteristics

    • And other timelike functions available in JavaScript (e.gDate.now) The difference is,window.performance.now()The timestamps returned are not limited to one-millisecond accuracy; instead, they represent the time as floating point numbers with accuracy up to microseconds.
    • The other difference is,window.performance.now()It increases slowly at a constant rate and is not affected by the system time (the system clock can be manually adjusted or tampered with by software such as NTP).

We can use this method to measure the execution time of the function, to achieve the effect of monitoring the execution efficiency of the function

const fun = () => { // do something } const startExcuteTime = window.performance.now(); fun(); const endExcuteTime = window.performance.now(); Console. log("fun function executed "+ (endExcuteTime - startExcuteTime) +" milliseconds.")Copy the code
  • GetEntries method: This method allows us to get the details of all resource requests on the page. The value returned varies depending on the parameters passed in. Each object is a description of the resource request process. When you call Performance. GetEntries () on the console, you can see how all the resources on the page are loaded.

Click on the elements in the array, each element details the time of the resource request key node, so we can fully use this to achieve resource request monitoring.

For more Api details, see the Performance interface article again

Simple realization of index calculation

A monitoring system can be roughly divided into the following stages, we will focus on the data collection stage. The data acquisition stage is designed into two points, one is data collection, the other is data reporting.

  • Data collection: Data collection relies on Performance Api to obtain Performance data. We can obtain the set of calculated values by referring to certain calculation indicators.
  • Data reporting: The collected data is reported to the server by sending an HTTP request. However, at present, because monitoring data is reported by XHR request, there are many restrictions, and data is easy to be lost and missed, which has certain impact on page performance. SendBecan is a browser solution to these problems by allowing the user agent to asynchronously send data to the server when the opportunity presents itself, without delaying the page load or affecting the loading performance of the next navigation. This solves all the problems of submitting analysis data: the data is reliable, the transfer is asynchronous, and the next page load is not affected. For details, please refer to developer.mozilla.org/zh-CN/docs/…

Below is a screenshot of Slardar’s source code. You can see that they reported monitoring data using sendBecan in preference and degraded to XHR request.

The Performance API allows you to calculate and report some of the metrics we often focus on

Redirection time = redirectEnd - redirectStart; DNS query time = domainLookupEnd - domainLookupStart; TCP connection duration = connectEnd - connectStart; Request time = responseEnd - responseStart; Dom tree parsing time = domcomplete-dominteractive; White screen time = responseStart - navigationStart; DOMready = domContentLoadedEventEnd - navigationStart; Onload time = loadEventEnd - navigationStart;Copy the code

Some of the existing web page performance detection tools

In addition to the first two ways to detect page performance, there are several third-party tools or platforms that provide detection capabilities.

  • LightHouse
  • PageSpeed
  • YSlow

The following is a screenshot of LightHouse. LightHouse not only generates some performance-related data, but also provides us with a series of optimization suggestions in addition to providing us with page performance detection. We can follow the suggestions to optimize websites or pages step by step.

  • React performance positioning tool

Provides component-level rendering analysis

React Performance measurement and analysis

React Profiler — React Blog

Performance Tool Test

At present, the project code of Xuelang teacher side runs in two large host environments, “CEF shell” and “browser”. In the first phase of the project, the overall project adopts the single-entry multi-channel mode, and the package of the project is not optimized, so the overall presentation is presented

  • Access clutter (browser can access a list of routes in CEF shell)
  • Messy packaging (multiple repeated packaging, resulting in slow compilation)
  • Confusing references (because it is a set of entries, many files are only referenced in CEF, and are referenced in a single entry file, causing the browser to load a series of unnecessary static resources)

As a result of the above series of problems, the overall page loading speed of wave learning is very slow. Subsequently, wave learning side specially organized a large reconstruction and optimization, and carried out the splitting of project entry and packaging process. On the whole, the current project structure of wave learning is multi-entry and multi-route, and distinguishes the host environment. Based on the current performance, the page loads much faster than before. The current load-time length for DomContentLoad in my current network situation is around 2S

Is there room for optimization to reduce page load times even further? We can look at Performance’s NetWork flame chart to see which files take longer to load and prolong the DomContentLoad trigger time. First, DomContentLoad event triggering is affected by HTML download, DOM parsing, JS script download & execution, all of which affect DomContentLoad triggering.

By observing the NetWork situation, it is obvious that the DCL is triggered after the loading of an encoding.js file is completed, and the loading time of this file is as long as 2.13s, which occupies about 80% of the loading time of the home page. So how to optimize the loading time of this script? There are several ideas

  • Compressing encoding.js makes it smaller (if not compressed)
  • Check if it is a home page strongly dependent file (if it is a subsequent dependency, you can use the asynchronous script defer or async to solve the DomContentLoad blocking problem)
  • See if it actually works (the best way is not to use 😈, which saves time completely)
  • Of course, there are a range of other strategies such as client caching, CDN acceleration, etc

I found out the reasons and ideas, so I started to trace the background of the file, and found that because this file is designed to deal with the pollfiy of some classroom SDK in different browsers, but now because of the separation of the big package & entrance in stage 1, the relevant resources of classroom SDK will not appear in the browser environment loading. So godless is actually no longer used in the browser environment and we can just delete it and see how it works. (The encoding.js file is not compressed, if the actual file is in use, we can use the compressed file.)

On the whole, the triggering time of DCL was reduced from 2.13s to 972ms, and the effect was quite obvious. Illustrate the use of related modules in the Performance panel with a small analysis case + a small optimization.

conclusion

This paper mainly introduces the use of tools to locate Performance problems and the calculation and statistics of some indicators by ourselves through the Performance Api. At present, Sladar in the company has provided us with relatively comprehensive data analysis. But understanding some of the basic tools and capabilities for positioning page performance is also helpful in day-to-day work.

Reference documentation

Juejin. Cn/post / 684490…

zhuanlan.zhihu.com/p/29879682

Juejin. Cn/post / 684490…

Xie. Infoq. Cn/article/daf…

Github.com/lizheng0515…

Developer.mozilla.org/zh-CN/docs/…

React Performance measurement and analysis

React Profiler — React Blog

❤️ Thank you

That is all the content of this sharing. I hope it will help you

Don’t forget to share, like and bookmark your favorite things.

Welcome to pay attention to the public number ELab team receiving factory good article ~

We are from the front end department of Bytedance, responsible for the front end development of all bytedance education products.

We focus on product quality improvement, development efficiency, creativity and cutting-edge technology and other aspects of precipitation and dissemination of professional knowledge and cases, to contribute experience value to the industry. Including but not limited to performance monitoring, component library, multi-terminal technology, Serverless, visual construction, audio and video, artificial intelligence, product design and marketing, etc.

Interested students are welcome to post in the comments section or use the internal tweet code to the author’s section at 🤪

Bytedance correction/social recruitment promotion code: APDJAY7

Post links: jobs.toutiao.com/s/dLLnGvr