preface
Chrome’s Performance panel gives us the ability to detect page Performance, but it provides much more than Performance data. This article will explore other information revealed by performance panel from the perspective of working principle, combined with the recording results of actual engineering.
The performance of the panel
You can refer to this article for details on the functions and usage of panels. This section describes the relationship between the browser architecture and the performance panel.
Since the final standard architecture has not yet been decided, the implementation details vary from browser to browser. Let’s take Chrome’s architecture as an example and compare it to the performance panel.The following figure shows the main threads represented by the performance panel. The performance panel does not contain all the threads in the architecture, but is mostly related to the page rendering process.
Network
Network represents the Network thread in the browser process, and we can see that the timeline contains the call information for all Network requests and file downloads, and identifies different types of resources in different colors.
Main
Main represents the Main thread in the rendering process, which does almost everything related to rendering: script execution, style calculation, layout calculation, drawing, etc.
Compositor & Raster
Compositor represents the Compositor thread in the renderer process and Raster represents the Raster thread in the renderer process. Now the browser draws a page, can be divided into the following steps:
- The main thread divides the page into layers (Update Layer Tree will be mentioned later)
- The raster thread rasterizes each layer separately
- The composition thread merges rasterized blocks into a single page
We can see in the performance panel that the main thread calls the raster thread at the end to do the actual rendering.
GPU
Obviously, this part is the GPU thread in the GPU Process.
Browser working report
Let’s take a look at the browser-recorded “work report” in roughly chronological terms.
Download and parse documents
The start of our journey will be from clicking on Chrome Performance PanelReloadButton (in the form of refresh) starts. The current page is uninstalled first, and with several logs reported, the browser begins to download index.html.Once the HTML document has been downloaded, the browser begins to apply index.html to the HTML standardparsingParse the received text string into DOM in the main thread. Notice that HTML parsing is not a seamless process, because HTML usually includes other external resources, such as images, CSS, JS, and so on. These files need to be retrieved through network requests or caching. Where, when the HTML parser parses to<script>
Tag, the parsing of the HTML document is stopped and the script is loaded, parsed, and executed. As you can see from the timeline of the main thread, the process to Parse HTML is episodic.
Processing of different resources
The following processing strategies can be seen in the main thread, but there is a big difference in the length of processing bars of different resources, so it is difficult to take screenshots, so it is not presented here.
What is the browser’s strategy for dealing with different resources?
- The Browser downloads the HTML and parses it, and if it encounters resources such as external CSS, it is downloaded by the Network thread in the Browser process
- The HTML parsing process can continue while the CSS is downloaded
- When parsing encounters an external Script tag (without async, defer properties), parsing stops until the Script is downloaded and executed
In general, the browser’s parsing of HTML will not be blocked by the download of CSS, IMG, etc., but the loading and execution of scripts will terminate the parsing of HTML. This is mainly due to potential problems such as JS changing the STRUCTURE of the DOM, or JS dynamically loading other JS and changing the DOM.
Obviously, although the browser can concurrently download resources from several network threads, if the above strategy is used only, when parsing to
Parsing execution of scripts
For complex business logic-heavy applications in the background, the performance cost of scripting is often the dominant factor. As you can see from the example below, removing beforeunload accounts for more than half of the time spent by the script itself. Parsing HTML is next, but other style calculations, microtasks, garbage collection, and so on are not the most painful. Of course, the example project itself is heavy on business logic, and the amount of JavaScript code determines its high cost.Sometimes we can consider usingasync
ordefer
Property to improve page performance, the difference between the two will not be repeated. It is important to note the dynamic addition of scripts. As shown in the sample code below, the script is appended to the document and begins to download by defaultasync
It has the same behavior, that is, “load first, execute first”.
let script = document.createElement('script');
script.src = "/xxx/a.js";
document.body.append(script);
Copy the code
If the async property is specifically set, the behavior of defer is “first loaded, first executed.”
function loadScript(src) {
let script = document.createElement('script');
script.src = src;
script.async = false;
document.body.append(script);
}
// Since async = false, big is executed first; Otherwise, execute small first
loadScript("/xxx/big.js");
loadScript("/xxx/small.js");
Copy the code
As you can see in the figure below, the appendChild method executed in the call stack is added dynamicallyscript
Script, and the download action begins shortly thereafter. After the dynamically loaded script is downloaded, the script is executed immediately.
Lifecycle and paint timing
This is shown belowThe articlePage life cycle flowchart as mentioned in. In this section, we compare Performance with this figure for observation.
beforeunload
Because the recording of Performance is reload on an existing page, the life cycle of the record begins with the unloading of the page. As shown in Main below,Beforeunload eventsFirst triggered by the browser. Notice that the yellow bar Event: beforeUnload is the browser-triggered activity we call itRoot Activities.
pagehide
Pagehide -> VisibilityChange -> Unload In fact, in the previous design of the browser, if the page was visible during the uninstall phase, visiBilityChange would be triggered after PageHide, as shown in the screenshot below. This leads to a different lifecycle and sequence of events for page unloading in different visual situations, which can lead to complexity for developers.In the future, the sequence of events in the uninstall phase will be unified, which is currently in progressissueUnder. As a result of this adjustment, unload is no longer recommended for code implementation.
first paint
First distinguish the following two time points:
- First paint: Refers to the time when the first pixel starts to paint on the screen, such as the background color of a page
- First Contentful paint: This is the time to start drawing content, such as text or pictures
From Performance, we can see the sequence of actions that are drawn for the first time (some of them snap quickly, so we don’t need screenshots) :
- CSS loading complete
- Parse Stylesheet: Parse Stylesheet to build CSSOM
- Recalculate Style: Recalculate the Style to determine the Style rules
- Layout: Determines the size and position of elements according to the calculation results
- Update Layer Tree: Updates the render Layer Tree
- Paint: Draw the page based on the Layer Tree (position, size, color, border, shadow, etc.)
- Composite Layers: the browser combines Layers and prints them to the screen
After the Layout process is very quick, here is some zoom to view:
DOMContentLoaded
DOMContentLoaded indicates that the HTML is fully loaded and parsed, although stylesheets, images, and other resources are not necessarily loaded. As you can see in the figure below, after multiple sections of HTML parsing, there is no other Parse HTML after the DCL.
pageshow/load
When navigation causes the browser to render a document in a window, the browser fires the PagesHow event on the window, as you can see here. Not only that, but when the page is first loaded, the PagesHow event fires after the Load event.
So going back to the Performance timeline, we can see from the figure below that after the red dotted line (marking load), the browser fires the PagesHow event, the root activity mentioned above.
Task and performance issues
Unfortunately, The Event Loop cannot be clearly identified by Performance. The gray Task in the following figure does not refer to the macro Task. It represents “The main thread is busy and cannot respond to user interaction”. Run Microtasks are really Microtasks that are executed at the end of a task. When we click on the call stack, we can see the callback function in the source code and the corresponding source code location.Task can be used to locate performance problems.RAIL modelIt tells us that we need to focus on complex tasks that consume more than 50ms of CPU to provide a coherent interactive experience. Of course, this is more of a response requirement for the interaction phase than it is necessarily for the initial loading phase.
conclusion
In this paper, from the perspective of working principle, combined with the recording results of practical engineering, a practical to theoretical knowledge test. Performance is not only a Performance analysis tool, but also a master learning machine to explore how browsers work. In general, the work of the browser is full and complex, which forms a contrast with our daily fishing, but still needs further study and thinking.
Refer to the link
[1] Measure performance with the RAIL model
[2] Get Started With Analyzing Runtime Performance
[3] Inside look at modern web browser
[4] JavaScript Start-up Performance
[5] How browsers work
[6] How the Browser Pre-loader Makes Pages Load Faster
The article can be reproduced at will, but please keep this link to the original text.
You are welcome to join ES2049 Studio. Please send your resume to [email protected].