From the browser multi-process to JS single-threaded, JS operating mechanism of the most comprehensive one comb

Source: Internet
Author: User
Tags setinterval

Objective

After the dragon looked up, March entered the third week. Today morning reading articles from @ NET to see the fish authorized to share.

The text starts from here ~

Recently found that there are a lot of JS single-threaded operation mechanism of the article, but found that a lot of information is only a part of the knowledge, and the different places of the statement is not uniform, easy to create confusion.

So prepare to comb this piece of knowledge, combined with the existing cognition, based on a large number of reference materials on the Web, from the browser to the JS single thread, the JS engine operating mechanism of the system comb again.

Show the form: because it is the system carding type, there is no more, but from beginning to end of the carding knowledge system, the focus is the key node of the knowledge points in tandem, rather than just analyze a part of knowledge.

Content is: From the browser process, and then to the browser kernel to run, and then to the JS engine single-threaded, and then to the JS event cycle mechanism, from beginning to end the system comb through, to get rid of fragmentation, forming a knowledge system

The goal is: After reading this article, the browser for many processes, JS single thread, JS event-cycle mechanism can have some understanding,
There is a knowledge system skeleton, not indefinitely feeling.

In addition, this article is suitable for a certain experience of the front-end staff, the novice please avoid the impact of excessive concept. Can be saved first, with a certain understanding and then look, can also be divided into many batches to watch, to avoid excessive fatigue. Outline

Distinguishing between processes and threads

Browsers are multi-process

What processes are included in the browser.

The advantages of a browser multi-process

Focus is on the browser kernel (rendering process)

Browser process and browser kernel (renderer process) communication process

Comb the relationship between the threads in the browser kernel

GUI render thread is mutually exclusive with JS engine thread

JS blocking page load

Webworker,js of multithreading.

Webworker and Sharedworker

Simply comb the browser rendering process

Load events and domcontentloaded events

Whether CSS loading will block DOM tree rendering.

Normal layers and composite layers

Talking about the operation mechanism of JS from event loop

The event cycle mechanism further complements

Say the timer alone.

SetTimeout, not setinterval.

Event loop Step by step: Macrotask and Microtask

Write in the last words distinguish between processes and threads

Thread and process are not clear, it is a lot of beginners will make mistakes, no relationship. This is normal. Let's look at the following image metaphor:

The process is a factory, the factory has its own independent resources-factories are independent of each other-threads are workers in the factory, multiple workers collaborate to complete the task-there is one or more workers in the factory-workers sharing space

and perfect The concept of perfection:

Factory resources-> System-allocated memory (separate piece of memory)-independent-> processes between factories separate from each other-multiple workers collaborate on tasks-> multiple threads to collaborate on tasks in a process-there are one or more workers in the factory-> A process consists of one or more threads-the shared space between workers-> the memory space (including code snippets, datasets, heaps, and so on) between the threads of the same process sharing the program.

And then consolidate the following:

If you are on a Windows computer, you can open Task Manager and you can see a list of background processes. Yes, that's where the process is viewed, and you can see the memory resource information and CPU share for each process.

So it should be easier to understand that a process is the smallest unit of CPU resource allocation (the system allocates memory to it)

Finally, describe it in more official terms:

Process is the smallest unit of CPU resource allocation (is the smallest unit that can have resources and run independently)

A thread is the smallest unit of CPU scheduling (a thread is a program-run unit that is built on a process and can have multiple threads in a process)

Tips:

Communication can also be between different processes, but at a much greater cost

Now, commonly used as the term: single-threaded and multithreading, are referred to in a single process and more. (So the core still has to belong to a process only) browsers are multiple processes

After understanding the difference between process and thread, the next step is to get a sense of the browser: (see simplified understanding first)

Browsers are multi-process

The browser is able to run because the system has allocated resources (CPU, memory) to its processes

In a simple sense, each tab is opened to create a separate browser process.

For verification of the above points, please click again on the first picture:

The diagram opens multiple tabs for the Chrome browser, and you can then see multiple processes in the Chrome Task Manager (each tab page has a separate process and a main process).

Interested can try, if more open a tab, the process will be more than 1 + (however, some versions of IE is a single process)

Note: Browsers should also have their own optimization mechanisms, and sometimes when you open multiple tabs, you can see in the Chrome Task Manager that some processes are merged (so each tab tag corresponds to a process that is not necessarily absolute) and which processes the browser contains.

Once you know that the browser is a multiple process, look at what processes it contains: (To simplify the understanding, just enumerate the main processes)

Browser process: The main process of the browser (responsible for coordination, master), only one. Functions are:

Be responsible for browser interface display, interact with user. such as forward, back, etc

Responsible for managing individual pages, creating and destroying other processes

Draws the bitmap in memory from the renderer process to the user interface

The management of network resources, download and so on

Third-party plug-in process: each type of plug-in corresponds to a process that is created only when the plug-in is used

GPU process: Up to one, for 3D rendering, etc.

Browser rendering process (browser kernel) (renderer process, internal multithreading): Default to each tab page a process, do not affect each other. Main function for

Page rendering, script execution, event handling, etc.

Enhanced Memory: Opening a Web page in a browser is equivalent to a new process (within the process has its own multithreading)

Of course, browsers sometimes merge multiple processes (for example, when you open multiple blank tabs, you'll find that multiple blank tabs are merged into a single process), as shown in

In addition, you can use Chrome's more tools to-> Task Manager to verify the advantages of multiple processes in the browser

Compared to a single process browser, multiple processes have the following advantages:

Prevent a single page crash from affecting the entire browser

Avoid third-party plug-ins crash affect the entire browser

Multi-processes take full advantage of multi-core advantages

Facilitate the use of sandbox model isolation plug-ins and other processes, improve browser stability

Simple to understand: if the browser is a single process, then a tab page crashes, affecting the entire browser, the experience is poor; Similarly, if it is a single process, the plug-in crashes will affect the entire browser, and many processes have many other advantages ...

Of course, memory and other resource consumption will be greater, a bit of space to change the meaning of time. focus is on the browser kernel (rendering process)

The point is, we can see that there are so many processes mentioned above, so what is the ultimate for a normal front-end operation? The answer is the rendering process.

You can understand this, the page rendering, JS implementation, the cycle of events, in this process. Next, focus on the process.

Keep in mind that the browser's rendering process is multi-threaded (if you don't understand this, look back at the process and thread distinctions)

Finally to the thread of this concept, good gracious. Then look at what threads it contains (enumerate some of the main resident threads):

GUI Rendering Threads

Responsible for rendering browser interface, parsing html,css, building dom tree and RenderObject tree, layout and drawing, etc.

When the interface needs to be redrawn (Repaint) or due to an operation that causes backflow (reflow), the thread executes

Note that the GUI rendering thread is mutually exclusive to the JS engine thread, and when the JS engine executes, the GUI thread is suspended (equivalent to being frozen), and the GUI update is saved in a queue until the JS engine is idle and executed immediately.

JS engine thread

Also known as the JS kernel, is responsible for processing JavaScript scripting programs. (e.g. V8 engine)

The JS engine thread is responsible for parsing JavaScript scripts and running the code.

JS engine has been waiting for the task queue in the arrival of tasks, and then processed, a tab page (renderer process) whenever there is only a JS thread running the JS program

Also note that the GUI rendering thread is mutually exclusive with the JS engine thread, so if the time of JS execution is too long, this will cause the page to render incoherent, resulting in page rendering loading blocking.

Event Trigger Thread

belong to the browser rather than the JS engine, used to control the event loop (can understand, JS engine itself is busy, need a browser to help other threads)

When the JS engine executes code blocks such as settimeout (or other threads from the browser kernel, such as mouse clicks, Ajax asynchronous requests, etc.), the corresponding task is added to the event thread

When the corresponding event matches the trigger, the thread adds the event to the end of the queue to be processed and waits for the JS engine to process

Note that because of the single-threaded relationship of JS, the events in these waiting queues have to be queued for JS engine processing (when the JS engine is idle to execute).

Timed Trigger Thread

The legendary setinterval and the settimeout of the online journey

The browser timer counter is not counted by the JavaScript engine (because the JavaScript engine is single-threaded, and if the blocking thread state affects the accuracy of the timing)

Therefore, the timer is timed and triggered by a separate thread (after the timer is completed, added to the event queue, wait for the JS engine to be idle and execute)

Note that in the HTML standard, the SetTimeout rules require that the time interval below 4ms be counted as 4ms.

Asynchronous HTTP Request Thread

After the XMLHttpRequest is connected, a new thread request is opened through the browser

When a state change is detected, if a callback function is set, the asynchronous thread generates a state change event and puts the callback into the event queue. And then executed by the JavaScript engine.

See here, if feel tired, you can take a rest, these concepts need to be digested, after all, the following will be mentioned the event loop mechanism is based on event-triggered threads, so if only to see a piece of knowledge of fragmentation, there may be a indefinitely feeling. To complete the comb can quickly precipitate, not easy to forget. Take a picture and consolidate it:


Again, why is the JS engine single-threaded? Well, there should be no standard answer to this question, for example, perhaps simply because of the complexity of multithreading, such as multithreaded operations are generally locked, so the original design of the choice of a single thread ... browser process and browser kernel (renderer process) communication process

See here, first of all, there should be some understanding of the processes and threads in the browser, and then talk about how the browser's browser process (the control process) communicates with the kernel,
Once this is understood, it is possible to concatenate this part of the knowledge and to have a complete concept from beginning to end.

If you open Task Manager yourself and then open a browser, you can see that there are two processes in Task Manager (one is the master process and one is the rendering process that opens the tab page).
And then, under this premise, look at the whole process: (a lot of simplification)

The browser process receives the user's request, first needs to obtain the page content (for example, downloading resources over the network), and then passes the task through the Rendererhost interface to the render process

The renderer interface of the renderer process receives a message, simply explains it to the render thread, and then starts rendering

The render thread receives the request, loads the Web page, and renders the page, which may require the browser process to acquire resources and require a GPU process to help render

Of course, there may be JS thread operation Dom (this may cause reflow and redraw)

Finally, the render process passes the results to the browser process

The browser process receives the results and draws the results

Draw a simple diagram here: (Very Simplified)

After reading this set of procedures, you should have a certain understanding of the operation of the browser, so that the foundation of the knowledge structure, after the subsequent easy to fill content.

This piece of talk to the depths of the browser is related to the core source resolution, does not belong to the scope of this article.

If this piece to dig deep, suggest to read some of the browser kernel source resolution article, or you can first look at the source of reference to the first article, write a good comb browser kernel thread between the relationship between the threads

Here, there has been a whole concept of the operation of the browser, and then, first of all, simply comb some concept GUI rendering thread and JS engine thread mutex

Because JavaScript is a manipulated DOM, if you modify these element properties while rendering the interface (that is, the JS thread and the UI thread run concurrently), the element data that is obtained before and after the render thread may be inconsistent.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.