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

Source: Internet
Author: User
Tags time interval

Reference article: https://segmentfault.com/a/1190000012925872

The article is comparatively long, the evil supplements the normal work will neglect the principle knowledge.

Now will feel more important points to comb down, strengthen the memory:

What process does the browser have?

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. function is responsible for browser interface display, and user interaction. such as forward, back, etc. responsible for the management of each page, create and destroy other processes in the renderer process to get the memory of the bitmap, drawing to the user interface network resources management, download and other Third-party plug-in process: Each type of plug-in corresponding to a process, only when the plug-in is used to create 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 role 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) two. The 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 thread is 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 some sort of operation that causes Backflow (reflow), the thread takes note that theGUI rendering thread is mutually exclusive to the JS engine thread , and the GUI thread is suspended when the JS engine executes (the equivalent is frozen), GUI updates are saved in a queue until the JS engine is idle and executed immediately.

JS engine thread is also known as the JS kernel, responsible for processing JavaScript script programs. (for example, 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 to deal with, a tab page (renderer process) whenever there is only a JS thread in the running JS program also note thatGUI rendering thread and JS engine thread is mutually exclusive , So if the time JS executes too long, this will cause the page rendering incoherent, resulting in page rendering load blocking.

The event-triggering thread belongs to the browser instead of the JS engine, which is used to control the event loop (it is understandable that the JS engine itself is busy and needs a different thread to help the browser) 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.), adds the corresponding task 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 threads legendary setinterval and settimeout the thread browser timer counter is not counted by the JavaScript engine (because the JavaScript engine is single-threaded and affects the accuracy of the timing if it is stuck in a thread state). Therefore, the timer is timed and triggered by a separate thread (after the timer has been added to the event queue, waiting for the JS engine to be idle) note that the Consortium stipulates in the HTML standard that the required time interval of less than 4ms in the settimeout is 4ms.

The asynchronous HTTP request thread, when XMLHttpRequest is connected by a new thread in 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 you feel tired, you can rest, these concepts need to be digested, after all, the following event loop mechanism is based on event-triggered threads, so if just looking at a fragment of knowledge,
There may be a feeling of indefinitely. 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 ... three. Communication process between the browser process and the browser kernel (renderer 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: (simplifying a lot) 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, briefly explained, to the render thread, and then starts rendering the render thread to receive the request, loading the page and rendering the page, which may require browser processes to acquire resources and require GPU processes to help render Of course, there may be JS thread operations dom (which may cause reflow and redraw) The last render process passes the results to the browser process browser process receives the results and plots 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 browser kernel source resolution article, or you can first look at the source of reference to the first article, write a good four. Comb the relationship between the threads in the browser kernel

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.

Therefore, in order to prevent the rendering unexpected results, the browser settings GUI rendering thread and JS engine for mutually exclusive relationship, when the JS engine executes GUI thread will be suspended,
GUI updates are saved in a queue until the JS engine thread is idle and executed immediately. JS blocking page load

From the above mutually exclusive relationship, you can deduce that JS if the execution time is too long will block the page.

For example, assume that the JS engine is doing a huge amount of computing, at this time even if the GUI is updated, it will be saved to the queue, waiting for the JS engine to perform after idle.
Then, because of the huge amount of calculation, so the JS engine is likely to be idle for a long time, will naturally feel the giant card incomparable.

Therefore, as far as possible to avoid JS execution time is too long, this will cause the page rendering incoherent, resulting in page rendering load blocking feeling. Webworker,js of multithreading.

The previous article mentioned JS engine is single-threaded, and JS execution time is too long will block the page, then JS really CPU-intensive calculation can do nothing.

Therefore, Web Worker was supported later in HTML5.

MDN's official explanation is:

Web worker provides an easy way to run scripts for Web content in a background thread. Threads can perform tasks without interfering with the user interface

a Worker is an object created with a constructor (e.g. Worker ()) running a named JavaScript file 

that contains code that will run in a worker thread; workers Runs in another global context, different from the current window

therefore, using the window shortcut to get the current global scope (instead of self) will return an error within a Worker

In this understanding: When creating a worker, the JS engine applies to the browser to open a child thread (the child thread is browser open, completely controlled by the main thread, and cannot manipulate the DOM). JS Engine threads communicate with worker threads in a particular way (PostMessage API, Need to interact with threads with specific data through serialization of objects

So, if there are very time-consuming work, please open a worker thread, so that no matter how the impact of the JS engine main thread,
After the results are calculated, the results are communicated to the main thread, perfect!

And note that theJS engine is single-threaded , the essence of this is still unchanged, the worker can understand is the browser to JS engine open plug-in, specifically to solve those large number of computational problems.

Others, the detailed explanation of the worker is not the scope of this article, so no longer repeat. Webworker and Sharedworker

Now that we're all here, let's mention Sharedworker (avoid the idea of confusing the two concepts later)

Webworker belong to only one page and will not be shared with other pages ' render processes (browser kernel processes) So chrome in the render process (every tab is a render process) creates a new thread to run the JavaScript program in the worker.

Sharedworker is shared by all pages of the browser and cannot be implemented in the same way as the worker because it is not part of a render process and can be shared with multiple render processes. So the Chrome browser creates a separate process for Sharedworker to run JavaScript programs, and there is only one sharedworker process in each of the same JavaScript in the browser, no matter how many times it is created.

See here, it should be easy to understand, is essentially the difference between process and thread. Sharedworker is managed by an independent process, and Webworker only belongs to a thread under the render process five. Simply comb the browser rendering process

Originally is directly planning to start talking about JS operation mechanism, but think, since the above all have been talking about the browser, jump directly to JS may be again abrupt, so, in the middle of the browser to add the rendering process (simple version)

In order to simplify the understanding, the prophase work is omitted directly: (to expand or completely can write another super long text)

-Browser input URL, browser master process to take over, open a download thread,
and then HTTP request (omit DNS query, IP addressing, etc.), and then wait for the response, get content,
The content is then forwarded to the renderer process via the Rendererhost interface

-The browser rendering process begins

When the browser kernel gets the content, the rendering can be divided into the following steps: Parsing HTML to build DOM tree parsing CSS Building render tree (parsing CSS code into a tree-like data structure, then combining DOM into render tree) layout render tree (layout/ Reflow), responsible for the size of each element, the calculation of the location of the render tree (paint), drawing the page pixel information browser will send the information of each layer to GPU,GPU will be synthesized (composite), displayed on the screen.

All the detailed steps have been omitted, after rendering is the load event, then is their own JS logic processing

Now that you have omitted some detailed steps, you may want to mention some of the details you might need to pay attention to.

Here redraw a diagram from the reference Source: (Reference source first)

load events and domcontentloaded events

The above mentioned, after rendering finished will trigger the Load event, then you can distinguish between Chu load events and domcontentloaded events.

Simply, know what they are defined on: When the domcontentloaded event is triggered, only when the DOM is loaded, not the style sheet, the picture.

(for example, if a async loaded script does not necessarily complete) when the OnLoad event is triggered, all the DOM, style sheets, scripts, and pictures on the page are already loaded.

(Finished rendering)

So, the order is: domcontentloaded-> load CSS load will block DOM tree rendering.

This is about the introduction of CSS in the head.

First, we all know thatCSS is downloaded asynchronously by a separate download thread.

And then again, the next few phenomena: CSS loading does not block DOM Tree parsing (DOM is built as usual when asynchronous loading) but blocks render tree rendering (CSS is loaded when rendering is required because the render tree requires CSS information)

This may also be an optimization mechanism for browsers.

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.