If I am the small boss that roadside sells fruit stand, encountered this problem, want to seek an answer as soon as possible. Depend! Small boss what all don’t know, only understood the front “say” two words, still can do? Baidu!

1. Check what JS is first.

Baidu results, the small boss understand, oh! JS is a scripting language. The ECMA International organization has developed a unified ECMAScrip standard for it. It is now mainly used for web development in browsers and server programming (Node.js)

  • Browser JS:JS = ECMAScript + DOM + BOM
  • Server Node.js:JS = ECMAScript + os + file + net + database

2. The boss redefined the question: “How does JS work in a browser?”

The small boss thought: “depend! The browser itself how to run I do not know, let alone browser JS “, so had to continue baidu.

After a search, the small boss learned that the application program in the computer is generally composed of multiple processes, and each process is composed of multiple threads. And the browser JS script execution, is responsible for a thread, is the JS engine thread.

3. The boss redefined the question: “Talk about the browserJS engine threadHow does it work?”

Small boss savvy is very high, immediately thought, to go deep into the analysis of JS engine thread running mechanism, it is better to understand first, including the thread of the process is how to run.

The JS engine thread is in the render process:

  • The Browser process
    • The browser’s main process (responsible for coordination and control), which has only one process
    • Responsible for browser interface display and user interaction. Forward, backward, etc
    • Responsible for page management, creating and destroying other processes
    • Draw a Bitmap in memory from the Renderer process onto the user interface
    • Network resource management, download, etc
  • Third-party plug-in processes
    • Each type of plug-in corresponds to a process that is created when the plug-in is used
  • GPU process
    • There is also only one process for 3D drawing and so on
  • Rendering process
    • Known as the browser kernel (Renderer process, with multiple threads inside)
    • Each Tab page has a rendering process that does not affect each other
    • The main function is page rendering, script execution, event processing and so on

4. The boss redefined the question: “Talk about the browserRendering processIn theJS engine threadHow does it work?”

What do not understand the small boss, have to continue baidu. First check to see when the render process will work.

Here’s a quick look at what happens when you type a URL into a web page:

  1. The DNS query
  2. A TCP connection
  3. An HTTP request is a response
  4. Server response
  5. Client-side rendering

In order to answer the question, the small boss now does not care about the first 4 browser actually do what. Obviously point 5 is where the render process comes in. For example, at point 4, the server responds with the following HTML file.

<! -- Small boss tone is more irritable, please understand ~ >
<! DOCTYPEhtml>
<html lang="en">
  <script>alert('Fire in the hold! ')</script>
  <body>
    <div>Son of Bittch!</div>
  </body>
</html>
Copy the code

Then the boss went one step further to understand the specific steps of the rendering process:

  1. Process HTML tags and build DOM trees.
  2. Process CSS tags and build CSSOM trees.
  3. Merge DOM and CSSOM into a render tree.
  4. Layout according to render tree to calculate geometric information for each node.
  5. Draw the individual nodes to the screen.

And two important threads in the rendering process:

  1. GUI rendering thread
    • Responsible for rendering browser interfaces, parsing HTML, CSS, building DOM trees and RenderObject trees, layout and drawing, etc
  2. JS engine thread
    • The JS engine thread is the JS kernel and is responsible for processing Javascript scripts
    • The GUI rendering thread is mutually exclusive with the JS engine thread, which blocks the GUI rendering thread

When parsing the HTML file above, the JS engine thread comes into play at step 1, when the GUI renderer parses to , directly to the JS engine thread processing. Here we are at last. JS execution blocks DOM builds, so let’s leave it at that).

4. The boss concludes again, redefining the problem: “Talk about the browserRendering processIn theJS engine threadThe operation of the<script>alert('Fire in the hold! ')</script>The mechanism?”

The boss, who still didn’t know anything, launched a clever interrogation: how does a computer read Javascript? To orangutans, after all, a code is just a string of symbols.

Small boss thought about it, this has what to say, since it is a single thread, the code can only be executed line by line. Fire in the hold! Bai.

At this point, the small boss realized that the problem should not be so simple. Learned a few JS phrases overnight:

setTimeout(() = > {
  console.log(0);
}, 1000);
new Promise((resolve) = > {
  console.log(1);
  resolve();
}).then(() = > {
  console.log(2);
});
console.log(3);
Copy the code

Boy, print order: 1320. Don’t talk about martial virtue at all. What about the order of execution?

Small boss here rational analysis of a wave: limited to single-threaded JS engine threads can only execute scripts synchronously, this point he is no doubt. The reason for not printing in order must be that the order of execution has changed. What causes the order of execution to change? After baidu, xiao Boss learned that the original JS engine thread execution mechanism: Event Loop.

5. The boss summed up the problem again: “Talk about the browserRendering processIn theJS engine threadIn theEvent LoopThe enforcement mechanism of”

What all don’t understand the small boss, after many studies (Baidu). See some of the reasons for the Event Loop mechanism.

1. WhyEvent LoopEnforcement mechanism.

For example, there is a demand, need to click the page, you can receive a red envelope. For example, the script code is as follows:

click(document.body) // JS with no Event Loop will get stuck waiting for the user to click
alert("Fuck you man!")
click(document.body) // Without Event Loop JS, the user is at the mercy of the application.
alert("Here, your red envelope!")
Copy the code

Small boss can only “synchronous implementation of JS” day ah 1: “you teach me to work?” Small boss can only operate in accordance with the order of the script, otherwise the page will be stuck, no user experience. The Event Loop implementation mechanism arises at the historic moment!!

2. Event LoopMechanism principle.

To solve the problem in point 1, under the Event Loop mechanism, tasks are divided into two types: synchronous tasks and asynchronous tasks. A synchronous task means executing a script one by one, in order. Scripts for asynchronous tasks are executed when notified that they can be executed.

To implement the function of asynchronous tasks, the Event Loop mechanism has an Event queue. When the script of the asynchronous task can be executed, the callback script is added to the end of the Event queue. When the code in the EXECUTION stack of the JS engine is finished, it will read the event queue and add the corresponding callback script of the asynchronous task to the execution stack. This process is called an Event Loop because it continues in a Loop.

After some baidu, small boss know that in the rendering process, there are other threads and JS engine threads collaboration.

Other threads in the render process:

  • Event trigger thread

    • Controls the event loop and manages a Task queue
  • Timing trigger thread

    • SetInterval and setTimeout are used to time and trigger timing
    • W3C stipulated in the HTML standard that setTimeout interval less than 4ms should be counted as 4ms
  • Asynchronous HTTP request threads

    • After the XMLHttpRequest connects, the browser opens a new thread request
  1. Why single thread?
  • JS is single-threaded because of its use in browsers. If you have two JS threads working on the Dom at the same time, one to delete a node and the other to modify it, which one should be used?
  1. How does a single thread handle an asynchronous task?

    • In fact, single-threaded JS can only execute tasks sequentially, one after the other. But in a browser, user interactions, data requests, require JS to execute specific code at specific times. Therefore, the collaboration of other threads is required.

The JS thread hands these tasks off to the event-triggering thread, which manages a queue of tasks and adds an event callback as soon as one of the tasks has a result. When the synchronization task of THE JS thread is completed, the system will query the event callback of the task list and add the tasks that can be executed to the execution stack.

Standing on the shoulders of giants

  • Browser rendering: Process and Rationale
  • More on the Event Loop
  • “Hardcore JS” understands how JS works at once