Browser kernel

Believe that most of the front end students are based on the Google code browser, IE is very few, Microsoft as early as a few years ago has expressed the hope that users don’t use IE browser, especially the old version, just as compatible with the tools to use, because of considering the need to use some old project, so keep in the system. Those of you who have done IE compatibility know how annoying IE is 🤦♂️, now we often use the mainstream kernel about these kinds:

  1. Chrome kernel: We all call Chrome kernel, formerly Webkit kernel, now Blink kernel
  2. Firefox kernel: Gecko kernel, commonly known as Firefox kernel
  3. Safari kernel: Webkit kernel

The browser kernel is multi-threaded, and a browser generally implements at least three resident threads:

  1. Javascript engine: based on event-driven single thread execution, JS engine has been waiting for the arrival of tasks in the task queue, and then to process, browser at any time only one JS thread running JS program.

  2. GUI rendering thread: Responsible for rendering the browser interface and executing when the interface needs to be rearranged, redrawn, or backflowed due to some operation. However, it is important to note that 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.

  3. 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 can come from the block of code currently executing by the JavaScript engine, such as setTimeOut, or from other threads in the browser kernel, such as mouse clicks, AJAX asynchronous requests, etc., but due to the single-threaded nature of JS all these events have to be queued up for the JS engine to process.

So how does the viewer render? From the time you enter the URL to the page rendering, the steps are roughly as follows:

  1. DNS resolves IP addresses
  2. Establishing a TCP Connection
  3. Sending an HTTP request
  4. Disabling a TCP Connection
  5. Browser rendering (emphasis only on this item)

Rendering Engine (GUI)

The tourist rendering process is roughly as follows:

  1. The GUI transforms HTML content into a DOM tree structure.
  2. The GUI converts the CSS stylesheet into a stylesheet that the browser can parse.
  3. Create element layout information.
  4. Build a hierarchical tree on the basis of 3.
  5. Generate a draw list for each layer and submit it to the composition thread. The composition thread divides the layer into blocks and rasterizes the blocks into bitmaps.
  6. The composite thread sends the draw block command to the browser process. The browser process generates the page on command and displays it on the monitor.

First, the GUI generates a DOM tree based on HTML, then combines it with the CSS tree for parsing to form the render tree, and then calculates the layout and drawing for the blueprint based on render. The first rendering of the page is completed.

Then, every time a new element is added to the DOM tree, the browser will use the CSS engine to scan the CSS stylesheet, find a style rule that matches the element, apply it to it, and then redraw it.

In ancient times, when JQ was still very popular, various DOM operations were packaged into a library to call a simple API, which dominated the front end of the time. In fact, DOM operations on the page performance cost is very high, because the browser will redraw after each DOM operation, change the layout will flow back. The emergence of VUE and React alleviates this problem by comparing old and new DOM trees with diff algorithms to update them.

JS engine

JS engine composition

  • The compiler. The main job is to compile the source code into an abstract syntax tree, and then, in some engines, into bytecode.

  • The interpreter. In some engines, the interpreter primarily accepts the bytecode, interprets and executes the bytecode, and then also relies on the recycle mechanism, etc.

  • JIT tools. A JIT – enabled tool that converts bytecode or abstract syntax trees into native code.

  • Garbage collector and profiler. They are responsible for garbage collection and collecting information from the engine to help improve engine performance and efficiency.

JS Event loop and event queue

Synchronous and asynchronous

When it comes to browser JS execution, we have to say JS event loop mechanism in the browser.

  1. All synchronization tasks are executed on the main thread, forming an execution stack.

  2. Outside of the main thread, there is a task queue. Whenever an asynchronous task has a run result, an event (callback) is placed in the task queue.

  3. When the synchronous task in the execution stack is finished, the system will read the events in the task queue, and those corresponding asynchronous tasks finish waiting state and enter the execution stack to start execution.

  4. The main thread repeats the above steps.

Therefore, all tasks can be divided into two types, one is synchronous task, the other is asynchronous task.

A synchronous task refers to a task that is queued to be executed on the main thread. The next task can be executed only after the first task is completed.

Asynchronous tasks are tasks that do not enter the main thread but enter the task queue. Only when the “task queue” notifies the main thread that an asynchronous task is ready to execute will the task enter the main thread.

Task queue

What about the various events stored in the task queue? First, they are divided into macro tasks and micro tasks.

Macro task Micro tasks
Who initiated Host (Node, browser) JS engine
Specific events Script, setTimeout/setInterval, UI Rendering /UI events, postMessage, MessageChannel, setImmediate, I/O (Node.js) Promise. Then, MutaionObserver
Who first run After running First run
Will a new Tick be triggered will Don’t

Here’s a simple question to understand:

const promise = new Promise((resolve, reject) = > {
  console.log(1);
  resolve('success')
  console.log(2);
});
promise.then(() = > {
  console.log(3);
});
console.log(4);
Copy the code

— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — be — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — –

⚠ Process analysis ⚠

  1. From top to bottom, encounter firstnew PromiseExecute synchronization code 1
  2. Meet againresolve('success')That will bepromiseTo change the state toresolvedAnd save the value
  3. Continue with sync code 2
  4. Jump out of thepromiseRun down, hitpromise.thenThis microtask, add it to the microtask queue
  5. Execute sync code 4
  6. This round of macro tasks are all executed, check the microtask queue, and findpromise.thenThe microtask and the state isresolvedExecute it.

In fact, many people confuse many concepts such as task queue and microtask queue, and even synchronous task, asynchronous task and macro task and microtask. In fact, JS could not initiate asynchronous request before there was no Promise, only synchronous task at that time.

Macro tasks, microtasks, and task queues (which hold event callbacks) are derived from asynchronous tasks.

Q&A

Q: Is there a one-to-one mapping between DOM tree nodes and render tree nodes? What nodes do DOM trees have that render trees don’t?

  1. DOM trees correspond one to one with HTML tags, including heads and hidden elements.

  2. The rendered tree does not include heads and hidden elements. Each line of a large text is a separate node, and each node has a corresponding CSS attribute.

Q: Does CSS block DOM parsing?

  1. For an HTML document, CSS, whether inline or linked, blocks subsequent DOM rendering, but not subsequent DOM parsing.

Q: What is the difference and relationship between redraw and rearrangement?

  1. Redraw: Redraw occurs when the appearance of elements in the rendered tree (e.g. color) changes without affecting the layout.

  2. Backflow: Redraw backflow occurs when the layout of elements in the render tree (e.g. size, position, hidden/state state) changes.

  3. Note: JS fetching Layout property values (e.g., offsetLeft, scrollTop, getComputedStyle, etc.) also causes backflow. Because the browser needs to calculate the latest value through backflow, backflow must cause redraw, and redraw does not necessarily cause backflow

Q: Do browsers delay JavaScript execution and DOM building when there are blocking CSS resources?

  1. When the browser encounters a script tag, DOM build is paused until the script completes execution.

  2. JavaScript can query and modify DOM and CSSOM.

  3. When CSSOM is built, JavaScript execution is paused until CSSOM is ready.

  4. Therefore, the position of the script tag is important. In practice, the following two principles can be followed:

  • CSS priority: CSS resources are introduced before JavaScript resources.
  • JavaScript should affect DOM building as little as possible.

Q: What about the blocking of CSS loading?

  1. CSS loading does not block parsing of the DOM tree

  2. CSS loading blocks DOM tree rendering

  3. CSS loading blocks the execution of subsequent JS statements

Q: Key render path details?

  1. Browser downloads the HTML file.

  2. The browser reads the HTML file and finds it contains an image, a CSS file, and a JS file.

  3. The browser starts downloading the image.

  4. The browser blocks rendering until the CSS and JS files are downloaded.

  5. The browser downloads the CSS file and parses it to make sure that there are no additional resources embedded (via import) that need to be recorded.

  6. The browser continues the group rendering until the js file is downloaded.

  7. The browser downloads the JS file and parses it to ensure that no additional resources need to be loaded.

  8. Finally, the browser renders the page.

conclusion

In fact, there are a lot of content about the browser rendering engine and JS engine can be said, we are interested in their own to expand, if you have better comments or questions, welcome to leave a message at any time, but also don’t forget to like attention to collect trivia 🤞.