preface
Have you ever seen how HTML, CSS, and JavaScript become pages? What is the browser doing behind the scenes? Understanding how browsers render is essential to further development, allowing us to think about performance optimization in a deeper, multi-dimensional way.
HTML, CSS, JavaScript data is processed by the intermediate rendering module, and finally displayed on the page (HTML hypertext Markup Language, CSS cascading style sheets, JS for JavaScript, we generally know what it is, those who have written web pages, most of the learners know).
- The content of HTML is made up of tags and text
- CSS, called cascading style sheets, is made up of selectors and properties
- JS can make the content of a web page “move”
Some people say that the rendering process can be divided into: DOM tree building, style calculation, layout stage, layering, drawing, chunking, rasterization and composition, etc. So the browser, just to review, it’s multithreaded, JS is single threaded, JS in the browser, it can be multithreaded.
The following topic around the browser rendering principle begins to describe, why to understand the browser rendering page mechanism? .
How browsers render
The rendering thread is responsible for rendering the browser interface, but the GUI rendering thread and the JS engine are mutually exclusive. When the JS engine executes, the GUI thread will be suspended, and GUI updates will be stored in a queue until the JS engine is idle.
So what is a DOCTYPE and what does it do
A DTD, or Document Type Definition, is a set of syntax rules that define XML or (x)HTML file types. Browsers use it to determine document types, decide which protocol to parse, and switch browser modes.
DOCTYPE is used to declare the document type and DTD specification, one of the main use is the document validity verification. If the file code is illegal, the browser will make some errors when parsing it.
Below is the browser rendering process:
Rearrangement Reflow
The definition of rearrangement: Each element in the DOM structure has its own box model, which requires the browser to evaluate and place the element where it should appear according to the various styles, a process called reflow.
Trigger Reflow condition
- Reflow or Repaint results when you add, delete, or modify Dom nodes
- When you move the DOM, or when you animate it
- When you modify the CSS style
- When you Resize the window, or when you scroll
- When you change the default font of a web page
Redraw Repaint
The definition of repaint, when the box position, size, and other properties such as color, font size, etc. have been determined, the browser then draws the elements according to their characteristics, and the page content appears. This process is called repaint.
Trigger the Repaint situation
- DOM changes
- The CSS changes
At this point, the following subdivision to say it!
A brief introduction to how the browser works
- Know the browser
Major browsers currently in use: Internet Explorer, Firefox, Safari, Chrome, Opera. Let’s look at the percentage of browser statistics:
Let’s talk about the main features of the browser:
A request is made to the server to display the web resource of your choice in a browser window. The resource usually refers to an HTML document, which can be a PDF, image, or other type. The location of resources is determined by the user using a URI (in computer terminology, a Uniform Resource Identifier (URI) is a string used to identify the name of an Internet Resource)
- Browser structure
- User interface: including address bar, forward and back buttons, bookmark menu, etc.
- Browser engine: Transmits instructions between the user interface and the rendering engine.
- Rendering engine: Responsible for displaying the requested content.
- Network: Used for network calls, such as HTTP requests; Its interfaces are platform independent and provide an underlying implementation for all platforms.
- User interface back end: Used to draw basic widgets, such as combo boxes and Windows. It exposes a common interface that is platform-independent, while underneath it uses the operating system’s user interface approach.
- JavaScript interpreter: Used to parse and execute JavaScript code.
- Data storage: This is the persistence layer. Browsers need to keep all kinds of data, such as cookies, on their hard drives. The new HTML specification defines a “web database,” which is a complete in-browser database.
Note: Each TAB in Chrome corresponds to an instance of the rendering engine, and each TAB is a separate process.
- The rendering engine
The rendering engine is “render” and is used to display the requested content on the browser screen.
Typically, a rendering engine can display HTML and XML documents and images, and other types of content can be displayed through plug-ins or browser extensions. Browsers (Firefox, Chrome, and Safari) are built around two rendering engines.
Firefox uses Gecko, while Safari and Chrome use WebKit, an open source rendering engine.
- Main process
The rendering engine will initially fetch the content of the requested document from the network layer, which is generally limited to 8000 blocks.
The rendering engine starts parsing the HTML document and turns each tag into a DOM node on the content tree. It also parses style data in external CSS files and style elements. Once the rendering tree is built, it enters the “layout” phase of processing, which assigns each node an exact coordinate that should appear on the screen.
- parsing
Parsing is an important context in a rendering engine. What is parsing?
Parsing a document means turning it into a meaningful structure that code can understand and use. The resulting structure is usually a tree of nodes that represents the structure of the document, which is called a parse or syntactic tree.
- grammar
Parsing is based on the syntax rules that the document follows. The process of parsing is divided into two sub-processes: lexical analysis and grammatical analysis.
What is lexical analysis?
Lexical analysis is the process of breaking up input into a large number of markers, markers (words in a language), the units that make up content. Equivalent to words in language.
What is grammatical analysis?
Grammatical analysis is the process of applying the grammatical rules of a language.
So, the general parsing work of the parser is divided into two components. The lexical analyzer (which is responsible for breaking the input content into valid tags) and the parser is responsible for analyzing the structure of the document according to the grammar rules of the language to build the parsing tree.
From source Document to Parse Tree: Document->Lexical Analysis->Syntax Analysis->Parse Tree
Parsing is an iterative process.
Instead, the parser asks the lexical parser for a new tag and tries to match it to some grammar rule. If the rule is matched, the parser adds the node corresponding to the tag to the parse tree and moves on to the next one.
But if there is no matching rule, the parser stores the tag internally and continues to request the tag until there is a matching rule, but if there is no matching rule, an exception is thrown (invalid document, contains syntax errors, and so on).
- translation
Parsing is usually in the process of translation, and translation is to convert the input document into another form, such as the compiler to compile the source code into machine code, the process is to parse the source code into a parse tree, and translate the parse tree into a machine code document.
Parsing-> Parsing Tree -> Translation -> Machine Code
- Parser type
There are two basic types of parsers: top-down and bottom-up parsers
Top-down: The parser starts at the higher level of the syntax and tries to find a matching structure.
Bottom-up is when the parser starts with low-level rules and gradually converts the input into syntax rules until the high-level rules are satisfied.
Do you know there is a tool called parser generator that can help you generate a parser by providing it with the syntax of the language you are using, i.e. terms and grammar rules, and it will generate the corresponding parser.
Are you dizzy? You can click here to see: the browser’s works: the new web browser reveal behind www.html5rocks.com/zh/tutorial…
Apply colours to a drawing mechanism
All the steps in the process from the browser receiving the page to the page displaying, called the key rendering path, are generally divided into two steps: page content loading completion and page resources completion, corresponding to DOMContentLoaded and Load respectively
Key: page rendering process is as follows, including page loading and page rendering two processes.
The page loading process is the process of requesting resources from the server and building a DOM tree. The page rendering process refers to rendering the view content through the DOM tree.
First, the browser loads the web content, uses the HTML interpreter to convert the web page into a series of tokens, and then builds a DOM tree based on the tokens. When a visible DOM node is inserted into the DOM tree, The browser builds a renderObject node and inserts it into the Render tree.
The Render tree contains the style information of the nodes, which can be easily understood as DOM + CSS. The Render tree is handed over to the layout engine, which calculates the size and location of each RenderObject node, before handing it over to the rendering engine to complete the content rendering of the page.
DOM + CSS -> Render Tree
A review of the entire key render includes:
- Parsing HTML to generate a DOM tree (DOM)
- The CSS is parsed to generate the CSSOM tree
- Combine DOM and CSSOM to generate rendere-tree
- Calculates the Layout of the render tree
- Render the layout to the screen Paint
So why do we need to know how browsers render pages?
Learn about rendering mechanics, mainly for performance optimization:
Understand how the browser loads, references to external style files, JS files, and puts them in the right place, is the fastest browser to get the file loaded; Learn how browsers parse, choose the best way to write, build DOM structures, and organize CSS selectors to improve browser parsing speed. Knowing how the browser renders can reduce the cost of “redrawing” and “rearranging”.
So the basic concepts that have emerged from the above mentioned rendering mechanics have been clarified:
- DOM: Document Object Model, the browser parse HTML into a tree of data structure
- CSSOM: CSS Object Model. The browser interprets the CSS into a tree data structure
- Render Tree: DOM and CSSOM are combined to generate a Render Tree
- Layout: Calculates the location of each node in the Render Tree
- Painting: Use the graphics card to display the contents of each node after Layout on the screen
When the browser gets the HTML file, it loads it from the top down, parses and renders it during loading. Loading is the process of getting resources; If an external CSS file or image is encountered during the loading process, the browser sends a separate request to obtain the CSS file or image. This request is asynchronous and does not affect the loading of the HTML file. However, if a JavaScript file is encountered, the HTML file suspends the rendering process and waits for the JavaScript file to load before continuing rendering.
Why wait for JavaScript?
Because JavaScript may modify the DOM, causing subsequent HTML resources to load in vain, we need to wait for the JavaScript file to complete loading before continuing rendering, so, the reason why JavaScript files are usually written at the bottom before the body tag.
Browser page rendering:
- Step 1: Create a DOM tree before the CSS resource is requested back.
- Step 2: After all the CSS requests come back, the browser will render the CSS in the order they were imported, and finally generate the CSSOM tree.
- Step 3: combine THE DOM TREE with the CSSOM TREE to generate the RENDER TREE with style and structure;
- Last step: The browser renders and parses the page according to the render tree
Because the rendering mechanism is too complex, the rendering module is divided into many stages in the execution process, through the “Browser working Principles and Practice” – rendering process is divided into: DOM tree construction, style calculation, layout stage; The rendering process is divided into layering, layer drawing, raster operation, composition and display.
The entire rendering process, from HTML to DOM, style calculation, layout, layering, drawing, rasterization, composition and display.
Interview question: Why build a DOM tree?
A: Because browsers can’t understand and use HTML directly, you need to transform HTML into a structure that browsers can understand, namely a DOM tree (tree structure is generally understood).
To see the complete DOM tree structure, open Chrome’s Developer Tools, or press F12, as shown below:
The next step is to get the DOM nodes to have the correct style, which requires style calculation.
The purpose of style calculation is to calculate the specific style of each element in a DOM node: three steps
- Convert CSS to a structure that browsers can understand
- Transform property values in the stylesheet to standardize them
- Figure out the specific style of each node in the DOM tree (referring to CSS inheritance and cascading rules)
When the rendering engine receives CSS text, it performs a conversion operation to convert the CSS text into a structure that the browser can understand — styleSheets. The process of standardizing attribute values: Converting all values into standardized computed values that the rendering engine can easily understand.
The DOM element’s final calculation looks like this:
The layout phase
Layout: Calculates the geometry of the visible elements in the DOM tree by first creating the layout tree (building a layout tree that contains only visible elements) and second computing the layout.
Interview question: Does CSS loading block page display?
- CSS loading does not block parsing of the DOM tree
- CSS loading blocks DOM tree rendering
- CSS loading blocks the execution of subsequent JS statements
So, in order to avoid users to see a long time of white screen time, should improve the loading speed of CSS.
To prevent THE CSS from blocking and causing a blank page, you can improve the page loading speed
- Use the CDN
- Compress the CSS
- Use caching wisely
- Reduce HTTP requests and merge multiple CSS files
Interview question: Downloading CSS files is blocking. Will it block DOM tree synthesis? Does it block the display of the page?
A: It will not block the DOM tree construction, because the HTML is converted to the DOM tree, and the file request is found in the network process to request the corresponding file, and the renderer continues parsing the HTML.
It will block the display of the page. When calculating the style, it needs to wait for the CSS file resource to perform cascading style. If the resource is blocked, it will wait until the network times out, the network reports an error, and the rendering process continues cascading style calculation.
Having covered the DOM generation, style calculation, and layout phases, let’s move on to the next phase.
Talk about layering: The rendering engine divides the page into many layers, which are stacked together in a certain order to form the final page. Once the layer tree is built, the rendering engine will draw each layer in the tree, drawing for the layer. This is followed by raster operations (draw lists are just lists of draw orders and draw instructions, whereas drawing is actually done by the compositing thread in the rendering engine), and finally compositing and displaying.
The page rendering mechanism is shown as follows:
The rendering process is shown below:
The browser renders as follows:
Two important concepts to mention (restate) here are reflux and redraw:
When a part of the Render Tree needs to be rebuilt due to changes in element size, layout, hiding, etc. This is called reflow.
Each page needs to be refluxed at least once, the first time the page loads.
On backflow, the browser invalidates the affected portion of the render tree and reconstructs that portion of the render tree. When backflow is complete, the browser redraws the affected portion of the render tree onto the screen, a process called redraw.
When some elements in the Render Tree need to update their attributes, these attributes only affect the appearance and style of the elements, not the layout, such as background-color. It’s called redrawing.
At the end of this article, I leave you with some interview questions: Why does reducing redrawing and rearranging improve Web performance? How can you reduce redrawing and rearranging?
The readings
- www.cnblogs.com/jianjie/p/1…
- zhuanlan.zhihu.com/p/26105913
- Working principle and practice of browser
- Segmentfault.com/a/119000001…
conclusion
The above is the content to talk about today, this article is only a brief introduction to Chrome rendering principle flow, thank you for reading, if you think this article is helpful to you, welcome to share it with more friends.
Denver annual essay | 2020 technical way with me The campaign is under way…