Ask me about the rendering principle of Chrome browser (6000 words long)

Time:2021-10-19

preface

Do you know how HTML, CSS and JavaScript become pages? What exactly does the browser do behind it? Let’s understand the rendering principle of the browser, which is essential to deeper development. It can let us consider performance optimization and other issues from a deeper level and multiple angles.

HTML, CSS and JavaScript data are processed by the intermediate rendering module and finally displayed on the page (including HTML hypertext markup language, CSS cascading style sheet and JS JavaScript. We generally know what it is. Most friends who have written web pages and learners know it).

  • The content of HTML is composed of tags and text
  • CSS, called cascading style sheets, consists of selectors and properties
  • JS can make the content of web pages “move”

Some people say that the rendering process can be divided into: DOM tree construction, style calculation, layout stage, layering, rendering, blocking, rasterization and synthesis. The browser reviews that it is multi-threaded, JS is single threaded, and JS can be multi-threaded in the browser.

Let’s start with the topic of browser rendering principle. Why do you want to understand the mechanism of browser rendering pages?.

Browser rendering principle

Firstly, the JavaScript engine is based on event driven single thread execution. 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 the GUI updates will be saved in a queue. It will not be executed until the JS engine is idle.

Ask me about the rendering principle of Chrome browser (6000 words long)

So what is DOCTYPE and its function

DTD, document type definition, is a series of syntax rules used to define the file type of XML or (x) HTML. The browser will use it to judge the document type, decide what protocol to use for parsing, and switch the browser mode.

DOCTYPE is used to declare document types and DTD specifications. One of its main purposes is to verify the legitimacy of files. If the file code is illegal, some errors will occur when the browser parses it.

The following figure shows the rendering process of the browser:

Ask me about the rendering principle of Chrome browser (6000 words long)

Rearrange reflow

Definition of rearrangement: each element in the DOM structure has its own box model, which requires the browser to calculate according to various styles and put the element where it should appear according to the calculation results. This process is called reflow

Trigger reflow

  • When you add, delete or modify DOM nodes, it will cause reflow or repeat
  • When you move the DOM position or do an animation
  • When you modify CSS Styles
  • When you resize the window, or when you scroll
  • When you change the default font of a web page

Repaint

The definition of redrawing. When the position, size and other attributes of various boxes, such as color and font size, are determined, the browser draws these elements according to their respective characteristics, and the content of the page appears. This process is called repaint.

Trigger repeat condition

  • DOM changes
  • CSS changes

That’s all, let’s break it down!

Briefly introduce the working principle of the browser

Ask me about the rendering principle of Chrome browser (6000 words long)

  1. Understanding browsers

Currently used mainstream browsers: Internet Explorer, Firefox, Safari, Chrome browser, opera. Let’s look at the proportion of browser statistics:

Ask me about the rendering principle of Chrome browser (6000 words long)

Let’s talk about the main functions of the browser:

It is to send a request to the server to display the selected network resources in the browser window. Resources generally refer to HTML documents, which can be PDF, pictures or other types. The location of the resource is determined by the user using a URI (in computer terminology,Uniform resource identifier(uniform resource identifier (URI) is a string used to identify the name of an Internet resource)

  1. Browser structure
  • User interface: including address bar, forward and backward buttons, bookmark menu, etc.
  • Browser engine: transfer 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 interface is platform independent and provides bottom implementation for all platforms.
  • User interface back end: used to draw basic widgets, such as combo boxes and windows. It discloses a general interface independent of the platform, and uses the user interface method of the operating system at the bottom.
  • JavaScript interpreter: used to parse and execute JavaScript code.
  • Data storage: This is the persistence layer. The browser needs to save various data on the hard disk, such as cookies. The new HTML specification defines “Web Database”, which is a complete in browser database.

Note: each tab of Chrome browser corresponds to a rendering engine instance, and each tab is an independent process.

  1. Rendering engine

The role of the rendering engine is “rendering”, which is used to display the requested content on the browser’s screen.

Generally, the rendering engine can display HTML and XML documents and pictures, and other types of content can be displayed through plug-ins or browser extensions. Browsers (Firefox, chrome and safari) are built based on two rendering engines.

Firefox uses gecko, while Safari and chrome use WebKit (an open source rendering engine).

  1. Mainstream process

At the beginning, the rendering engine will get the content of the requested document from the network layer, and its size is generally limited to 8000 blocks.

The rendering engine will start parsing the HTML document and convert each tag into a DOM node on the content tree one by one. It also parses the style data in external CSS files and style elements. After the rendering tree is built, it will enter the “layout” processing stage, that is, assign each node an exact coordinate that should appear on the screen.

  1. analysis

Parsing is an important environment in the rendering engine. What is parsing?

Parsing a document refers to transforming the document into a meaningful structure that can be understood and used by the code. The parsed structure is usually a node tree representing the document structure, which is called parsing tree or syntax tree.

  1. grammar

Parsing is based on the syntax rules followed by the document. The parsing process is divided into two sub processes: lexical analysis and grammatical analysis.

What is lexical analysis?

Lexical analysis is the process of dividing the input content into a large number of tags, which are the units of content. Equivalent to a word in a language.

What is parsing?

Grammar analysis is the process of applying the grammar rules of a language.

So, the parsing work of the parser is generally divided into two components: lexical analyzer (responsible for decomposing the input content into valid tags). The parser is responsible for analyzing the structure of the document according to the syntax 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.

Well, the parser requests a new tag from the lexical analyzer and tries to match it with a syntax rule. If the rule is matched, the parser will add the node corresponding to the tag to the parse tree, and then continue to the next one.

However, if there is no matching rule, the parser will store the tag internally and continue to request the tag until there is a matching rule. However, if there is no until, an exception will be thrown (invalid document, syntax error, etc.).

  1. translate

Parsing is usually in the process of translation, and translation is to convert the input document into another form. For example, the compiler compiles the source code into machine code. The process is to parse the source code into a parsing tree and translate the parsing tree into machine code documents.

Compilation process: source code – > parsing – > parse tree – > Translation – > machine code

  1. Parser type

There are two basic parser types: top-down parser and bottom-up parser

From top to bottom:The parser starts from the high-level structure of syntax and tries to find the matching structure.

Bottom up is:Starting from the low-level rules, the parser gradually converts the input content into syntax rules until the high-level rules are met.

Do you know a tool called parser generator, which can help you generate a parser. You just provide it with the syntax of the language you use, that is, vocabulary and syntax rules, and then you will generate the corresponding parser.

Are you dizzy? You can click here to see how the browser works: behind the scenes secrets of the new web browser
https://www.html5rocks.com/zh…

Rendering mechanism

The browser starts from receiving the page to displaying the page. All steps in the whole process are called critical rendering path, which is generally divided into two steps: page content loading completion and page resource completion, corresponding to domcontentloaded and load respectively

Key: the rendering process of web pages is as follows, including page loading and page rendering.

Page loading is the process of requesting resources from the server and building a DOM tree. Web page rendering refers to rendering the view content through the DOM tree.

Ask me about the rendering principle of Chrome browser (6000 words long)

DOM + CSS -> Render Tree

Review the whole key rendering, including:

  • Parse HTML and generate DOM tree (DOM)
  • Parse CSS and generate cssom tree
  • Merge Dom and cssom to generate a render tree
  • Calculate the layout of the render tree layout
  • Render layout to screen

Ask me about the rendering principle of Chrome browser (6000 words long)

So, why do you want to understand the browser’s page rendering mechanism?

Understand the rendering mechanism, mainly for performance optimization:

Understand how the browser loads. When referencing external style files and JS files, put them in the appropriate position, which is the fastest speed for the browser to complete the file loading; Understand how the browser parses, select the best writing method, build the DOM structure, and organize CSS selectors in order to improve the parsing speed of the browser; Understanding how the browser renders can reduce the consumption of “redraw” and “re layout”.

So, we have been talking about understanding the rendering mechanism and several basic concepts. Let’s understand them first:

  • DOM: document object model. The browser parses HTML into a tree data structure
  • Cssom: CSS object model. The browser parses CSS into a tree data structure
  • Render tree: merge Dom and cssom to generate render tree
  • Layout: calculate the specific location of each node in render tree
  • Painting: render the node contents after layout to the screen through the graphics card

Ask me about the rendering principle of Chrome browser (6000 words long)

Ask me about the rendering principle of Chrome browser (6000 words long)

About browser page rendering:

  • Step 1: create a DOM tree before the CSS resource is requested back;
  • Step 2: when all CSS requests come back, the browser will render in turn according to the import order of CSS, and finally generate cssom tree;
  • Step 3: combine the DOM tree and cssom tree to generate a render tree with style and structure;
  • The last step: the browser renders and parses the page according to the rendering tree

From known rendering engines and critical rendering paths

Ask me about the rendering principle of Chrome browser (6000 words long)

Ask me about the rendering principle of Chrome browser (6000 words long)

Because the rendering mechanism is too complex, the rendering module is divided into many stages in the execution process. Through the browser working principle and practice – rendering process, it is divided into: building DOM tree, style calculation and layout stages; The rendering process is divided into: layering, layer rendering, rasterization, synthesis and display.

The whole rendering process, from HTML to DOM, style calculation, layout, layer, drawing, rasterization, synthesis and display.

Interview question: Why build a DOM tree?

A: because the browser cannot directly understand and use HTML, so it needs to convert HTML into a structure that the browser can understand, that is, DOM tree (the tree structure is generally understood).

To understand the complete DOM tree structure, you can open the “developer tool” of chrome or press F12, as shown below:

Ask me about the rendering principle of Chrome browser (6000 words long)

Next, to make the DOM node have the correct style, you need style calculation.

The purpose of style calculation is to calculate the specific style of each element in the DOM node: three steps

  • Transform CSS into a structure that browsers can understand
  • Convert and standardize attribute values in the style sheet
  • Calculate the specific style of each node in the DOM tree (involving CSS inheritance rules and cascading rules)

When the rendering engine receives CSS text, it will perform a conversion operation to convert the CSS text into a structure that the browser can understand – stylesheets. The process of attribute value standardization: convert all values into standardized calculated values that are easy to understand by the rendering engine.

The final calculated style of DOM element is shown in the figure below:

Ask me about the rendering principle of Chrome browser (6000 words long)

Layout stage

Layout: calculate the geometric position of visible elements in the DOM tree. First, create a layout tree (build a layout tree containing only visible elements), and second, calculate the layout.

Interview questions:Will CSS loading block page display?

  • CSS loading does not block DOM tree parsing
  • CSS loading will block the rendering of DOM trees
  • CSS loading will block the execution of the following JS statements

So, in order to avoid allowing users to see a long white screen time, the loading speed of CSS should be improved.

In order to prevent CSS from blocking and causing page white screen, the page loading speed can be improved

  • Using CDN
  • Compress CSS
  • Make rational use of cache
  • Reduce HTTP requests and merge multiple CSS files

Interview questions:Downloading CSS file is blocked. Will it block the synthesis of DOM tree? Will it block the display of the page?

Ask me about the rendering principle of Chrome browser (6000 words long)

After talking about the three stages of DOM generation, style calculation and layout, let’s talk about the later stages.

Talk about layering: the rendering engine divides the page into many layers. These layers are superimposed together in a certain order to form the final page. After the construction of the layer tree is completed, the rendering engine will draw each layer in the layer tree and draw for the layer. Then rasterize (the drawing list is only used to record the drawing order and drawing instructions, but in fact, the drawing operation is completed by the synthesis thread in the rendering engine), and finally synthesize and display.

Find an overall flow chart as follows:
Ask me about the rendering principle of Chrome browser (6000 words long)Ask me about the rendering principle of Chrome browser (6000 words long)

The page rendering mechanism is shown as follows:
Ask me about the rendering principle of Chrome browser (6000 words long)

The rendering process diagram is as follows:
Ask me about the rendering principle of Chrome browser (6000 words long)

The browser rendering process is as follows:
Ask me about the rendering principle of Chrome browser (6000 words long)

The flow chart of three things parsed by the browser is as follows:

One is HTML / SVG / XHTML
Ask me about the rendering principle of Chrome browser (6000 words long)
Second, CSS
Ask me about the rendering principle of Chrome browser (6000 words long)
The third is JavaScript script
Ask me about the rendering principle of Chrome browser (6000 words long)

It’s important to say (again)Two concepts: reflow and redraw

When a part of render tree needs to be rebuilt due to changes in element size, layout, hiding, etc. This is called reflow.

Each page needs at least one reflow, that is, when the page is first loaded.

During reflow, the browser will invalidate the affected part of the rendering tree and reconstruct this part of the rendering tree. After reflow, the browser will redraw the affected part to the screen, and the process becomes redrawing.

When some elements in render tree need to update attributes, these attributes only affect the appearance and style of the elements, but will not affect the layout, such as background color. It’s called redrawing.

At the end of this article, some interview questions are left:Why can reducing redrawing and rearrangement optimize web performance? How can we reduce redrawing and rearrangement?

summary

The above is what I want to talk about today. This article only briefly introduces the rendering principle and process of Chrome browser. Thank you for reading. If you think this article is helpful to you, you are also welcome to share it with more friends.

Recommended Today

The VBA ide displays a project that is not open. The solution cannot be operated

Reading time |0.24 minutes word count |388 characters primary coverage |1. Introduction & background “VBA ide displays the project that is not open, and the solution cannot be operated” Author | SCscHero Writing time | 2021/12/29 PM7:28 Article type |Series Degree of completion |Completed motto Every great cause has a trivial beginning. 1、 Introduction & […]