The main function of the browser is to present the web resource selected by the user. It needs to request the resource from the server and display it in the browser window. The format of the resource is usually HTML, but also includes PDF, image, and other formats.

Browser threads

Browsers are multithreaded and work with each other under kernel control to keep them in sync. A browser implements at least three resident threads: JavaScript engine threads, GUI rendering threads, and browser event-firing threads.

  • GUI rendering thread: Responsible for rendering the HTML elements of the browser interface, which is executed when the interface needs to be repainted or reflow due to some action. While the Javascript engine runs the script, the GUI rendering thread is suspended, that is, “frozen.”

  • JavaScript engine threads: Are responsible for processing JavaScript scripts

  • Timer trigger thread: The browser timer counter is not counted by the JavaScript engine, which is single-threaded. If the JavaScript engine is blocked, it will affect timing accuracy, so the browser uses a separate thread to time and trigger timing.

  • Event trigger thread: When an event is triggered, the thread adds the event to the end of the queue, waiting for the JS engine to process it. These events include currently executing code blocks such as scheduled tasks, other threads in the browser kernel such as mouse clicks, AJAX asynchronous requests, and so on. All of these events are queued up for processing by the JS engine due to the single-threaded nature of JS. Timing blocks For any asynchronous task such as an Ajax request, the event-triggering thread simply puts the callback function into the event queue when the timed time or the Ajax request succeeds.

  • Asynchronous HTTP request thread: When XMLHttpRequest opens a new thread through the browser after the connection and a state change is detected, if a callback function is set, the asynchronous thread generates a state change event and places it in the JavaScript engine’s processing queue for processing. When an asynchronous request is made, the HTTP request thread is responsible for requesting the server. After receiving the response, the event-triggering thread places the return function on the event queue.

Browser Rendering process

1. Parse HTML and build DOM tree; Parsing CSS produces a CSS rule tree

The browser parses the source code of the HTML document and constructs a DOM tree. The DOM tree is a deep traversal process in which all the children of the current node are built before the next sibling of the current node is built.

The browser parses the content of the CSS file. Generally speaking, the browser will first look for the inline styles, then the styles defined in the CSS file, and finally the default styles of the browser to build the CSS Rule Tree.

2. Construct render tree

Rendering Tree is constructed according to DOM Tree and CSSOM Tree. Note: Rendering Tree is not the same as DOM Tree, because something like Header or display: None doesn’t need to be in the Rendering Tree.

3. The render tree has been created

With Render Tree, browsers already know what nodes are in a web page, the CSS definition of each node, and their dependencies to figure out where each node is on the screen.

4. Painting the render tree

According to the calculated rules, through the graphics card, draw the content on the screen.

5. Reflow

When the browser finds that something has changed that affects the layout and needs to go back and re-render, the process is called reflow. Reflow will recursively calculate the geometry and position of all nodes starting from the root frame.

6. Repaint

Changing an element’s background color, text color, border color, and so on does not affect the attributes of its surrounding or internal layout, and a portion of the screen is redrawn, but the element’s geometry remains the same.

Browser rules for CSS and JS parsing

CSS:

  • Placing CSS in head blocks rendering of the page (rendering of the page will wait until THE CSS is loaded)
  • CSS blocks JS execution (because GUI threads and JS threads are mutually exclusive, because it is possible for JS to manipulate CSS)
  • CSS does not block the loading of external scripts (it does not block the loading of JS, but the execution of JS, because browsers always have pre-scanners)

JS:

  • Directly introduced JS blocks rendering of the page (GUI thread and JS thread are mutually exclusive)
  • Asynchronously loaded JS (with the defer attribute added to the script tag) does not block parsing of the page
  • Asynchronously loaded JS (add async property to script tag) download process does not block page parsing, immediately after the download is complete, the execution process will block page parsing
  • JS does not block loading of resources
  • JS executes sequentially, blocking subsequent JS logic execution

HTML page loading and parsing process

  1. The user enters the url (let’s say it’s an HTML page and it’s visiting for the first time), the browser makes a request to the server, and the server returns an HTML file.
  2. The browser starts loading the HTML code and finds a < link > tag inside the < head > tag that references an external CSS file;
  3. The browser requests a CSS file, and the server returns the CSS file. (Meanwhile, the GUI rendering thread continues to execute without affecting each other)
  4. The browser continues to load the < body > part of the HTML, and with the CSS file in hand, starts rendering the page;
  5. The browser finds an < img > tag in the code that references an image and sends a request to the server. Instead of waiting for the image to download, the browser continues to render the code that follows;
  6. The server returns the image file, and the browser needs to go back and re-render that part of the code because the image takes up a certain amount of space and affects the layout of the following paragraphs.
  7. The browser finds a < script > tag containing a line of Javascript code and runs it directly;
  8. A Javascript script that operates on an element instructs the browser to hide a tag in the code (style.display= “None”). The browser rerenders the code;
  9. When < / HTML > is encountered, the process ends;
  10. When the user interacts with the page and the browser finds that some part of the page has changed and the layout is affected, the browser reflow. The browser repaints an element when it changes its background color, text color, border color, and other properties that do not affect its surrounding or internal layout.

HTML page loading optimization

  • Page weight loss. Page size is the most important factor affecting loading speed. Remove unnecessary whitespace and comments. To move inline scripts and CSS to external files, you can use HTML Tidy to slim down HTML, and you can use compression tools to slim down JavaScript.

  • Reduce the number of files. Reducing the number of files referenced on a page reduces the number of HTTP connections. Many JavaScript and CSS files can be merged.

  • Reduce domain name queries. DNS lookup and domain name resolution is also time-consuming, so reduce references to external JavaScript, CSS, images and other resources, the use of different domain names as little as possible;

  • Cache reuse data;

  • Optimize the page element loading order. First load the page’s original content and associated JavaScript and CSS, then load the DHTML related content, such as images, flash, video, etc., which are not originally relevant resources loaded last;

  • Reduce the number of inline JavaScript. The browser parser assumes that inline JavaScript will change the structure of the page, so using inline JavaScript is expensive. Don’t use document.write() to output content. Use modern W3C DOM methods to process page content for modern browsers;

  • Use modern CSS and legal tags. Use modern CSS to reduce labels and images, for example, use modern CSS+ text can completely replace some pictures only with text, use legal tags to avoid browser parsing HTML to do “error correction” and other operations, but also can be HTML Tidy to give HTML weight;

  • Do not use nested tables;

  • Specifies the size of the image and tables. If the browser can immediately determine the size of the image or tables, it can display the page without having to rearrange the layout, which not only speeds up the display of the page, but also prevents improper layout changes after the page has finished loading.

Refer to the article

  1. The rendering process of a web page in a browser
  2. Performance optimization – LOADING and execution of CSS and JS
  3. Browser rendering principle and process