当前位置:网站首页>Use performance to see what the browser is doing
Use performance to see what the browser is doing
2022-06-26 13:46:00 【zz_ jesse】
Preface
Chrome Browser's Performance Panels provide us with the ability to detect page performance , But it provides more than just some performance data . This article will be from the perspective of working principle , Combined with the recording results of the actual project , Explore the other information that the performance panel has revealed to us .
Performance panel
About the function and usage of the panel , You can refer to this article [1]. This section mainly introduces the relationship between browser architecture and performance panel .
Because the final standard architecture has not yet been determined , The implementation details of each browser are different . Here we have Chrome The architecture of , Compare the architecture to the performance panel .
From the figure below, we can see the main threads presented by the performance panel . The performance panel does not contain all the threads in the architecture , Mainly related to the page rendering process .
Network
Network Represents the network thread in the browser process , We can see that the timeline contains all the call information for network requests and file downloads , And identify different types of resources with different colors .
Main
Main Represents the main thread in the rendering process , It's all about rendering basic things , Script execution 、 Pattern calculation 、 Layout calculation 、 Drawing and so on .
Compositor & Raster
Compositor Represents the compositing thread in the rendering process ,Raster Represents the grid thread in the rendering process . Now the browser draws a page , It can be divided into the following steps :
The main thread divides the page into layers ( It will be mentioned later Update Layer Tree)
Grid threads rasterize each layer separately
The composition thread merges the rasterized blocks into a page
We can see , In the performance panel, the main thread finally invokes the raster thread to render the actual rendering .
GPU
obviously , This part is GPU Process Medium GPU Threads .
Browser work report
Next, we're going to look roughly at the time dimension , Take a look at the browser recording 「 The work report 」.
Download and parse the document
The starting point of our journey will be from clicking on Chrome Performance Panel Of Reload[2] Button ( It's like refreshing ) Start . The current page is unloaded first , With several log reports , The browser started index.html Download work for .
HTML After downloading the document , The browser starts to follow HTML Standard pair index.html To analyze [3], In the main thread, the received text string is parsed as DOM . We can notice that ,HTML The process of parsing is not done in one go , This is because HTML Other external resources are usually included , Such as images 、CSS、JS etc. . These files need to be retrieved by network request or cache . among , When HTML The parser resolves to <script> When labeling ,HTML The parsing of the document stops , Instead, load 、 Parsing and executing scripts . therefore , You can see from the timeline of the main thread that ,Parse HTML The process is intermittent .
The treatment of different resources
The following processing strategies can be seen in the main thread , However, there is a big gap between the length and length of different resources , The screenshots are difficult , There's no presentation here .
So what are the browser's processing strategies for different resources ?
Browser download HTML And analyze , If it comes to the outside CSS And so on , It will be by Browser In process network Thread Download
When CSS When the download ,HTML The parsing process can continue
When parsing encounters the outside Script label ( It doesn't contain async、defer attribute ) when , Parsing stopped , Until the script is downloaded and executed
in general , The browser to HTML The parsing process will not be CSS、IMG The download of resources is blocked , But the loading and execution of the script stops HTML Parsing . This is mainly because JS May change DOM Structure , Or is it JS Dynamically load other JS Re change DOM And other potential problems .
obviously , Although the browser can be concurrent several network Threads download resources , But if you just deal with it like the above strategy , When it comes to <script> when , If the file is large or the latency is high , It could happen 「 The script monopolizes the thread and no other resources are being downloaded 」 The empty window period of (idle network). therefore ,pre-loader[4] ( perhaps preload scanner And so on ) Will be outside the main thread , Scan the rest of the tags , make the best of network Thread downloads other resources . This mechanism can be optimized 19\%[5] Load duration of .
Script parsing execution
For the complex background application of heavy business logic , The performance overhead of scripting , It's often the dominant . We can see from the example below that , Remove beforeunload Previous uninstall , Scripts themselves account for more than half of their time . analysis HTML In the second place , As for other style calculations 、 Micro task 、 Garbage collection, etc , It's not the most painful place . Of course , The example project itself focuses on business logic ,JavaScript The amount of code determines its high cost .
Sometimes we can consider using async perhaps defer Property to improve page performance , The differences between the two will not be repeated . What needs to be specified is the dynamic addition of scripts . As shown in the following example code , The script is append Once in the document, it will start to download , And default and async Having the same behavior , namely 「 Load first and execute first 」.
let script = document.createElement('script');
script.src = "/xxx/a.js";
document.body.append(script);
Copy code If you set up async attribute , Will follow defer Come on , namely 「 Load first, execute first 」.
function loadScript(src) {
let script = document.createElement('script');
script.src = src;
script.async = false;
document.body.append(script);
}
// because async = false, So do it in sequence big; otherwise ( Usually first ) perform small
loadScript("/xxx/big.js");
loadScript("/xxx/small.js");
Copy code As you can see from the following figure , Call stack execution appendChild Method added dynamically script Script , Soon after, the download started . After downloading the dynamically loaded script , The first time to start script execution .

lifecycle and paint timing
The following figure shows the article [6] Page lifecycle flowchart mentioned in . In this section we combine Performance, Look at the picture .
beforeunload
because Performance Is recorded on an existing page reload, So the life cycle of the record starts with the unloading of the page . Here's the picture Main Shown ,beforeunload event [7] First triggered by the browser . It can be noted that , Yellow bar Event: beforeunload It's an activity triggered by the browser itself , We call it root activity (Root activities)[8].
pagehide
We can notice from the figure below that , Why is the sequence of events triggered inconsistent with the above lifecycle flowchart , yes pagehide -> visibilitychange -> unload Well ? in fact , In the design before the browser , If the page is visible during the unload phase ,visibilitychange Will be in pagehide Trigger later , As in the screenshot below . This makes the page unload in different visual situations , There is an inconsistent life cycle and sequence of events , Bring complexity to developers .
In future new versions of browsers , The sequence of events in the unload phase is unified , At present, the progress is in this issue[9] Next . Because of the adjustment of this part ,unload It is no longer recommended to use in code implementation .
first paint
First distinguish the next two time points :
first paint: It refers to the time when the first pixel begins to draw on the screen , For example, the background color of a page
first contentful paint: It's about the time to start drawing content , Such as text or pictures

from Performance in , We can see the first series of actions drawn ( Some of the process is very fast , The screenshots save ):
CSS Loading complete
Parse Stylesheet: Parsing style sheets , build CSSOM
Recalculate Style: Recalculate style , Determine style rules
Layout: According to the calculation results, the layout is carried out , Determine the size and location of elements
Update Layer Tree: Update render layer tree
Paint: according to Layer Tree Draw page ( Location 、 size 、 Color 、 Frame 、 Shadow, etc )
Composite Layers: Composite layer , The browser merges layers and outputs them to the screen
Layout After that, the process is very fast , Zoom in here to see :
DOMContentLoaded
DOMContentLoaded Express HTML Has been fully loaded and parsed , Of course, stylesheets 、 Images and other resources may not have been loaded yet . As you can see from the following figure , After many paragraphs HTML After the parsing ,DCL After that, there was nothing else Parse HTML 了 .
pageshow/load
When navigation causes the browser to render a document in a window , The browser will be in window Trigger on pageshow event , Please refer to here for specific timing [10]. More Than This , When the page is first loaded ,pageshow The event will be in load Trigger after event .
So back to Performance Time axis , We can see from the figure below , In the red dotted line ( Mark the load) after , Browser triggered pageshow event , This is the root activity mentioned above .
Mission and performance issues
It's a pity that ,Performance It's not clear that Event Loop. The gray one in the picture below Task Not macro tasks , It stands for 「 The main thread is busy at present , Unable to respond to user interaction 」;Run Microtasks It's really a micro task at the end of a task . When we click on the call stack to observe , You can see the callback function in the source code and the corresponding source location .
adopt Task Can locate performance problems .RAIL Model [11] Tell us we need to focus on occupancy CPU beyond 50ms The complex task of , To provide a coherent interactive experience . Of course , Here is more about the response requirements of the interaction phase , It's not necessarily a requirement for the initial loading phase .
summary
From the perspective of working principle , Combined with the recording results of the actual project , A practical test of theoretical knowledge was carried out .Performance It's not just a performance analysis tool , Or explore the browser working principle of the little overlord learning machine . in general , The work of the browser is substantial and complex , In contrast to our daily fishing experience , We still need to deepen our study and thinking .
About this article
come from :ES2049
https://juejin.cn/post/6904582930174705677
边栏推荐
- Taishan Office Technology Lecture: four cases of using bold font
- Traverse the specified directory to obtain the file name with the specified suffix (such as txt and INI) under the current directory
- HW蓝队溯源流程详细整理
- Original code, inverse code and complement code
- VTK 圆柱体的生成与渲染
- Thinking caused by the error < note: candidate expectations 1 argument, 0 provided >
- Nlp-d60-nlp competition D29
- LeetCode_ Stack_ Medium_ 150. evaluation of inverse Polish expression
- Aesthetic experience (episode 238) Luo Guozheng
- Some conclusions about Nan
猜你喜欢
随机推荐
Ring queue PHP
Zero basics of C language lesson 7: break & continue
Es common grammar I
shell脚本详细介绍(四)
Learn how to develop owl components by hand (7): practical use of owl projects
I have a good word to say, and I admire myself
Beifu PLC based on NT_ Shutdown to realize automatic shutdown and restart of controller
HW蓝队溯源流程详细整理
Connection migration for DataGrid configuration
Firewall introduction
Here Document免交互及Expect自动化交互
Wechat applet - bind and prevent event bubble catch
[node.js] MySQL module
【Proteus仿真】Arduino UNO按键启停 + PWM 调速控制直流电机转速
es常用语法一
mysql配置提高数据插入效率
[shell] generate strings between specified dates
7-3 minimum toll
微信小程序注册指引
MongoDB系列之Window环境部署配置










