current position:Home>Browser parsing process, process and thread, performance optimization
Browser parsing process, process and thread, performance optimization
2021-08-27 06:40:22 【Demon present】
Page loading order
// 3
window.onload = function () {
// The trigger condition : All resources are loaded ( contain DOM TREE/CSS/ Pictures and other resources )
console.log(document.getElementById('box'));
};
// 2
window.addEventListener('DOMContentLoaded', function () {
// The trigger condition :DOM TREE Loading is complete
console.log(document.getElementById('box'));
});
// 1
setTimeout(() => {
console.log(document.getElementById('box'));
}, 0);
Copy code
After a page is accessed from the server , The browser gets the page source code , Then do something
1. Generate DOM TREE => Yes HTML To deal with
be based on HTTP Get stream file ( Hexadecimal code )
Compile the binary code into specific characters
according to TOKEN To analyze ( lexing )
Generate layer specific nodes ( Element nodes / Text node ...)
Generate a... According to the nested relationship with each other DOM Trees ( Node tree )
2. Generate CSSOM TREE => Yes CSS To deal with
3. Generate RENDER TREE ( Render tree )
DOM TREE + CSSOM TREE = RENDER TREE
For start set to display:none Style elements are not generated in the rendering tree ( Start loading the page. These elements are not rendered )
4. Layout / backflow / rearrangement Layout
Calculate the position and size of each element in the viewport according to the rendering tree
5. layered
Layer according to the calculated style
location
Set transparency RGBA
Set filter
Text exceeds box size , We cut it
...
Calculate the drawing list of each layer separately ( How to draw )
----------> All the above operations are entrusted to “GUI Rendering thread ” To complete
6. draw / Repaint Painting
Submit the generated drawing list to “ Composite thread ”
“ Composite thread ” Do our final drawing , Render on the browser page
Copy code
Processes and threads
process : A program ( Creating a new page card in the browser is a process ) 【 factory 】
Threads : A process may contain multiple threads , Each thread can do one thing at a time 【 Worker 】
To really do many things at the same time, we must rely on Multithreading ( Browsers are multithreaded )
however JS It's single threaded [ Because the browser itself only allocates one thread “GUI Rendering thread ” function JS Code ]
JS In essence, you can't do more than one thing at the same time
Sync : Last thing done , Go to the next thing
asynchronous : The last thing was not done ( Let's do some special treatment ), The next thing to do [ But definitely not JS Can handle two things at the same time ]
Browser layer DOM TREE/CSSOM TREE... The process is also single threaded “GUI Rendering thread ”( Cooperate with the browser's multithreading to complete some things , for example : Resource request is the use of the browser HTTP Network threads do )
Copy code
Browser specific parsing process “GUI Rendering thread ”
1. Parse all... From top to bottom HTML label / After various nodes ,DOM TREE It was generated
2. But there will be some special problems in the process
link href='xxx.css' Outer chain
=> The browser will assign a new HTTP The network thread loads the resource file
=> Will not hinder DOM Rendering of trees
<style> ... </style> embedded
=> No need to request new resource files , But at this time, the style has not been processed , The browser will make a record , It will wait for all CSS After the resource is loaded , Render in order CSS, To generate CSSOM Trees
@import 'xxx.css' Import type
=> Although it is also a distribution network HTTP Thread to load the resource file
=> But at this time GUI The rendering thread will be blocked [ hinder DOM Tree rendering ]( Only wait for the resources to load back , Will continue to render DOM)
encounter script Embedded js Code
=> Execute now JS( hinder DOM TREE Rendering of )
encounter script Outside the chain js Code
=> hinder DOM TREE Rendering of , Assign one at the same time HTTP Thread to load the resource file
=> Execute immediately after loading JS
=> If JS Asynchronous is not used in , Direct access to DOM Elements , and DOM The element has not been rendered yet ,JS It's impossible to get
encounter img
=> Older browsers will hinder DOM Rendering
=> Although the new browser will not hinder DOM Rendering , However, the request for image resources will occupy HTTP Threads ( The browser can only open 6~7 individual HTTP Threads , This picture / The loading of audio and video resources would have been slower , Will affect other resources link/script And so on )
=> The rendering of picture resources is also more time-consuming than general resources , It will also slow down the rendering speed of the page
...
Copy code
performance optimization
1. no need @import
2. link Put it in HEAD in ( Load the resource file as early as possible , Wait like this DOM The tree is rendered , Resources may also be loaded back ): The mechanism of contemporary browsers is becoming more and more perfect ,Webkit Browser prediction parsing :chrome Preload scanner html-preload-scanner By scanning the nodes “src” , “link” Equal attribute , Preload after finding external connection resources , Avoid waiting time for resource loading , It also realizes early loading and separation of loading and execution
3. If CSS Less code , Use embedded as much as possible , Can reduce the HTTP request ; But if there are many styles , Embedded type is adopted , First load HTML Will waste a long time , This might as well be based on link Load separately ; Mobile terminal development is embedded first ( Of course, we should also consider CSS Code quantity );
4. Reduce DOM Or reduce DOM Hierarchical nesting of , And label semantics ...( Contemporary front-end development , Start with the structure of the first screen / Write it out , Rendering is just the first screen , When the first screen is loaded , When the page scrolls , Then based on the JS Create the structure and content of other screens => Skeleton screen /SSR => Client skeleton screen , At the beginning, there was no first screen structure , only one loading Or just a bitmap ...)
5. hold script Put it at the bottom of the page ( Render first DOM TREE, Re execution JS, You can also get DOM Element ), It can also be based on events DOMContentLoaded/load Wait until the structure is loaded to get DOM Elements
6. async / defer to script Set properties
=>async Is to open up HTTP Thread loading resource file , here DOM TREE continue , But once the resource file is loaded back , stop it DOM TREE, Execute first JS Code ( Don't consider JS Order of introduction , Whoever loads it first will execute it first )
=>defer Also open up HTTP Thread loading resource file , Even if the resource file is loaded back , Will be waiting for DOM The tree is rendered , And then according to JS The import order of is executed in turn JS( Incompatible with older browsers )
7. Picture merge (Sripte)/ BASE64( Easy to use, but use with caution ) / iconfont(CSS draw ) / svg
=> Lazy loading of pictures
....
8. CRP(critical rendering path) Browser critical path node optimization
Copy code
copyright notice
author[Demon present],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2021/08/20210827064017975u.html
The sidebar is recommended
- Crazy blessing! Tencent boss's "million JVM learning notes", real topic of Huawei Java interview 2020-2021
- JS JavaScript how to get the subscript of a value in the array
- How to implement injection in vuex source code?
- JQuery operation select (value, setting, selected)
- One line of code teaches you how to advertise on Tanabata Valentine's Day - Animation 3D photo album (music + text) HTML + CSS + JavaScript
- An article disassembles the pyramid architecture behind the gamefi outbreak
- BEM - a front-end CSS naming methodology
- [vue3] encapsulate custom global plug-ins
- Error using swiper plug-in in Vue
- Another ruthless character fell by 40000, which was "more beautiful" than Passat and maiteng, and didn't lose BMW
guess what you like
-
Huang Lei basks in Zhang Yixing's album, and the relationship between teachers and apprentices is no less than that in the past. Netizens envy Huang Lei
-
He was cheated by Wang Xiaofei and Li Chengxuan successively. Is an Yixuan a blessed daughter and not a blessed home?
-
Zhou Shen sang the theme song of the film "summer friends and sunny days" in mainland China. Netizen: endless aftertaste
-
Pink is Wangyuan online! Back to the peak! The new hairstyle is creamy and sassy
-
Front end interview daily 3 + 1 - day 858
-
Spring Webflux tutorial: how to build reactive web applications
-
[golang] walk into go language lesson 24 TCP high-level operation
-
August 23, 2021 Daily: less than three years after its establishment, Google dissolved the health department
-
The female doctor of Southeast University is no less beautiful than the female star. She has been married four times, and her personal experience has been controversial
-
There are many potential safety hazards in Chinese restaurant. The top of the program recording shed collapses, and the artist will fall down if he is careless
Random recommended
- Anti Mafia storm: He Yun's helpless son, Sun Xing, is destined to be caught by his dry son
- Introduction to flex flexible layout in CSS -- learning notes
- CSS learning notes - Flex layout (Ruan Yifeng tutorial summary)
- Today, let's talk about the arrow function of ES6
- Some thoughts on small program development
- Talk about mobile terminal adaptation
- Unwilling to cooperate with Wang Yibo again, Zhao Liying's fans went on a collective strike and made a public apology in less than a day
- JS function scope, closure, let, const
- Zheng Shuang's 30th birthday is deserted. Chen Jia has been sending blessings for ten years. Is it really just forgetting to make friends?
- Unveil the mystery of ascension
- Asynchronous solution async await
- Analysis and expansion of Vue infinite scroll source code
- Compression webpack plugin first screen loading optimization
- Specific usage of vue3 video play plug-in
- "The story of huiyeji" -- people are always greedy, and fairies should be spotless!
- Installing Vue devtool for chrome and Firefox
- Basic usage of JS object
- 1. JavaScript variable promotion mechanism
- Two easy-to-use animation JS that make the page move
- Front end Engineering - scaffold
- Java SQL Server intelligent fixed asset management, back end + front end + mobile end
- Mediator pattern of JavaScript Design Pattern
- Array de duplication problem solution - Nan recognition problem
- New choice for app development: building mobile applications using Vue native
- New gs8 Chengdu auto show announces interior Toyota technology blessing
- Vieira officially terminated his contract and left the team. The national security club sent blessings to him
- Less than 200000 to buy a Ford RV? 2.0T gasoline / diesel power, horizontal bed / longitudinal bed layout can be selected
- How does "heart 4" come to an end? Pinhole was boycotted by the brand, Ma Dong deleted the bad comments, and no one blessed him
- We are fearless in epidemic prevention and control -- pay tribute to the front-line workers of epidemic prevention!
- Front end, netty framework tutorial
- Xiaomi 11 | miui12.5 | android11 solves the problem that the httpcanary certificate cannot be installed
- The wireless charging of SAIC Roewe rx5 plus is so easy to use!
- Upload and preview pictures with JavaScript, and summarize the most complete mybatis core configuration file
- [25] typescript
- CSS transform Complete Guide (Second Edition) flight.archives 007
- Ajax foundation - HTTP foundation of interview essential knowledge
- Cloud lesson | explain in detail how Huawei cloud exclusive load balancing charges
- Decorator pattern of JavaScript Design Pattern
- [JS] 10. Closure application (loop processing)
- Left hand IRR, right hand NPV, master the password of getting rich