Relations browser front-end mechanisms and processes threads of knowledge (a)

Read a great God blog, front-end learning system suddenly Ming Wu up. So ready to start the system with reference to the pace of the god of learning. Blog link: https: //segmentfault.com/a/1190000013662126.

Very often asked after input from url address, what happens? Many times the answer is very general, not have their own core, so learning about the big ideas of God, but the following summary of the backbone, will only have to learn every part, so that is a body of knowledge to a good understanding of the structure and the relationship between the upper and lower .

1. Receive url from the browser to open (the relationship between the mechanisms and processes and threads can expand this part of the browser) network request thread

2. Turn on the network to issue a complete thread http request (in this section relate to dns query, tcp / ip request, five Internet protocol stack and other knowledge)

3. a request received from the server back to the corresponding receiving the request (this part may relate to load balancing, interception and handling inside the safety background, etc.)

4. http background and foreground interaction (Cookie optimization, and this codec portion comprises the http header, response code, packet structure, Cookie, etc. knowledge, can provide static resources, such as gzip compression)

5. carry out a separate cache problem, http cache (which caches a head portion including http, etag, catch-control, etc.)

6. The browser receives the parsed data packet flow after http (html- lexical analysis and parsing to parse tree dom, css parse tree generated css rules, combined into render tree and layout, painting rendering, synthetic composite layer, the GPU drawing, outside the chain of processing resources, and loaded domcontentloaded etc.)

7. The CSS visual formatting model (render rule element, such as a block containing the control block, BFC, IFC concepts)

8. JS parsing engine (JS interpretation stage, the pretreatment stage, execution stage generates an execution context, VO, scope chain, recovery mechanisms, etc.)

9. Other (can be extended knowledge of different modules, such as cross-domain, web security, hybrid mode and much more

The first part: the browser process and the relationship between process threads

First, the browser process

First, we look at the concept of official processes and threads.

  • The process is the smallest unit cpu resource allocation (the smallest unit is able to have the resources and run independently)
  • A thread is the smallest unit of cpu scheduling (threads is based on a process of running the unit, a process can have multiple threads)

Then we are multi-process browser, each open a Tab page, create the equivalent of a stand-alone browser process. The browser includes several of the following major processes:

  1. Browser process: the master process browser, there is only one. Acts

    • Responsible browser interface display, interaction with the user. Such as forward, backward, etc.
    • Responsible for the management of each page, create and destroy other processes
    • The memory Renderer process resulting in Bitmap, draw on the user interface
    • Network resource management, and other downloads
  2. Third-party plug-in process: one for each type of plug-in process, only when using the plug-in creates
  3. GPU process: at most one for 3D rendering, etc.
  4. Browser rendering process (browser kernel) (Renderer process, the interior is multithreaded): Each Tab page by default a process, independently of each other. The main role

    • Page rendering, script execution, event handling, etc.

And in the process so much browser rendering process most important, because it includes many threads, and these threads have played a major role in the implementation of the displayed page rendering. Here are some of the main threads:

  1. GUI rendering thread

    • Responsible for rendering browser interface, parsing HTML, CSS, DOM tree and build a tree RenderObject, layout, and drawing and so on.
    • When the interface needs to be repainted (Repaint) or due to some operation raises reflow (reflow), the thread will execute
    • Note, GUI rendering thread and JS engine threads are mutually exclusive , when the JS engine executes the GUI thread is suspended, GUI updates are stored in a queue when the JS engine idle until immediately be executed.
  2. JS engine thread

    • Also known as JS kernel, handles Javascript script.
    • JS engine thread is responsible for parsing Javascript to run the code.
    • JS engine has been waiting for the arrival of the mission task queue and then process, a Tab page (renderer process) no matter what time only one thread running JS JS program
    • Also note, the GUI rendering thread and JS engine threads are mutually exclusive , so if JS execution time is too long, this will cause the page to render incoherent, leading to load the page rendering blocked.
  3. Event trigger thread

    • Attributable to the browser rather than the JS engine to control the event loop (understandable, JS engines themselves are busy, we need to open another thread assistance)
    • When added to the engine block of code when JS as setTimeOut (other threads may be the kernel from the browser, such as a mouse click, AJAX asynchronous request, etc.) will correspond to an event task thread
    • When the corresponding event meets the trigger condition is triggered, the thread will add events to be processed end of the queue, waiting to be processed JS engine
    • Note that because the single-threaded relationship JS, so these pending events queue had queued for processing the JS engine (only to carry JS engine when idle)

  4. Timing trigger thread

    • Legendary setIntervaland setTimeoutwhere the threads
    • Browser timer counter is not counted by the JavaScript engine, (because JavaScript engine is single-threaded, if the state is in blocking the thread will affect the exact timing of the note)
    • (Executed after the count-up, added to the event queue, waiting for the JS engine idle) and therefore trigger timing clocked by a separate thread
    • Note that, in the W3C HTML standard stipulates requirements setTimeout lower than 4ms 4ms interval is calculated.
  5. Asynchronous http request thread

    • In XMLHttpRequest request after the connection is through a browser to open a new thread
    • When the state change is detected, if provided with a callback, asynchronous thread to produce state change events , the callback and then placed in the event queue. And then executed by the JavaScript engine.

So so many threads, what does it matter between them?

First GUI rendering thread and the thread mutually exclusive JS engine

Because JavaScript is steerable DOM, and if at the same time rendering interface to modify these elements attributes (ie JS thread and UI thread running at the same time), then the elements of the data obtained before and after the rendering thread could not match up.

Therefore, in order to prevent the emergence of unexpected results rendering, browser settings GUI rendering thread and JS engine as mutually exclusive relationship, when the JS engine executes the GUI thread is suspended,
GUI updates will be stored in a queue until the JS engine Now it is executed when the thread is idle.

JS blocking page loading

From the above exclusive relationship can be derived, JS If the execution time is too long will block the page.

For example, assume that a huge amount of calculation JS engine ongoing, even at this time GUI updates, will be stored in the queue, waiting to be executed after the engine idle JS.
Then, due to the huge amount of computing, it is likely JS engine to idle after long, long time, will naturally feel very huge card.

Therefore, to avoid JS execution time is too long, this will cause the page to render incoherent, leading to load the page rendering feels blocked.

 

Then the next process is the master process control Browser process of rendering process.

  • Browser process receives a user request, we first need to get the page content (such as downloaded through the network resources), then pass the tasks RendererHost interfaces to Render process
  • Renderer Renderer interface to receive the message after the process is simple to explain, to the rendering thread, and then start rendering

    • Rendering thread receives the request, the page load and render pages, which may require access to resources and processes required Browser GPU rendering process to help
    • Of course, there may be a JS-threaded operating DOM (This may cause reflux and redraw)
    • Finally Render process will result to the Browser process
  • Browser process receives the results and drawn.

js operating mechanism

Finally, since js is single-threaded, so the mission will naturally have a sequence, called the task queue, all tasks need to line up, before the end of a mission, will perform a post-task. If a task takes a long time ago, a task after it had been waiting for. So the task is divided into two types of synchronization tasks: that is queued for execution on the main thread task, only the first task is finished, you can perform a task after. The other is asynchronous tasks: refers not to enter the main thread, and enter the "Task Queue" (task queue) tasks, only "task queue" notify the main thread, an asynchronous tasks can be carried out, the task will enter The main thread execution.

Overall, he's operating mechanism is as follows:

(1) All synchronization tasks are performed on the main thread to form a stack execution (execution context stack).
Addition (2) the main thread, there is a "Task Queue" (task queue). With asynchronous tasks run as long as a result, an event is placed in the "task queue" at home.
(3) Once the "execution stack" all synchronization task is finished, the system will read the "task queue" to see what events there. Those corresponding asynchronous tasks, thus ending the wait state, into the execution stack, started.
(4) the main thread is repeated the third step above.

As long as the main thread empty, it will go read "Task Queue", which is the operational mechanism of JavaScript. This process will be repeated.

When the main thread running, producing heap (heap) and stack (stack), the stack of code calls various external API, they are added to various events (click, load, done) in "Task Queue" in. As long as the stack of code is completed, go to the main thread will read "Task Queue", followed by the implementation of those events corresponding to the callback function.

Next, look at an example:

< Script > 
        the console.log ( ' Start ' ) // synchronize tasks on the main thread of execution, into the execution stack.
        the setTimeout ( function () {// asynchronous task into the task table, until after 0 seconds into the task queue.
            console.log ( ' setTimeout1 ' );
        }, 0);
        the console.log ( ' End ' ); // synchronize tasks on the main thread of execution, into the execution stack.
</ Script >

So the results of this program are:

However, we do general tasks are divided into synchronous and asynchronous tasks can not be very precise to every event, so on this basis, we divided the task of macro and micro-tasks.

  • macro-task (macro task): Code including the overall script, setTimeout, setInterval
  • micro-task (micro tasks): Promise, process.nextTick

So now enforcement mechanisms becomes:

  • Execute a macro task, if you encounter during the micro-task, it will be placed in the task [micro] in the event queue
  • After the completion of the current macro task execution, the task will be to see [micro] event queue, and which are all micro-executing the task order

The synchronous and asynchronous tasks Tasks task of combining micro-macro task, is more accurate js operation mechanism. Then look at the network Pirates:

  • When the whole script (a macro as the first task) begins execution, all of the code will be divided into two parts: the "sync task", "asynchronous tasks";
  • Synchronization tasks directly into the main thread in order to perform;
  • Asynchronous tasks will be divided into micro and macro tasks task;
  • Macro task into the Event Table, the callback function is registered and in which, whenever the specified event is completed, this function will move the Event Table Event Queue in;
  • Micro task will enter into another Event Table, the callback function is registered and in which, whenever the specified event is completed, this function will move the Event Table Event Queue in;
  • When the task is completed execution in the main thread, the main thread is empty, checks micro tasks Event Queue, if there are tasks, they all perform, at a macro task if there is no implementation;
  • The above process will be repeated, this is the Event Loop Event Loop;

Next, look at an example:

< Script > 
        the setTimeout ( function () {// the setTimeout is asynchronous, and the function macro, macro function into the queue
            console.log(1)
        });
        new new Promise ( function (Resolve) {// new new Promise synchronization task is directly performed, printing 2, and the for loop
            console.log ( 2 );
            for ( were in =  0 ; in <  10000 ; of ++ ) {
                i == 9999 && resolve();
            }
        }). the then ( function () {//promise.then micro task into the task queue micro
            console.log(3)
        });
        the console.log ( . 4 ); //console.log(4) synchronization task, perform direct printing. 4
     </ Script >

Two of the first cycle synchronization tasks executed, the print 2,4, micro task queue next checks found .then function, thus performs the function to print out 3. Then perform asynchronous tasks setTimeout, then print it out 1.

So the end result is 2,4,3,1.

The next upgrade of difficulty, see Example 2:

 <script>
        function add(x, y) {
            console.log(1)
            setTimeout(function () { // timer1
                console.log(2)
            }, 1000)
        }
        
        add();

        setTimeout(function () { // timer2
            console.log(3)
        })

        new Promise(function (resolve) {
            console.log(4)
            setTimeout(function () { // timer3
                console.log(5)
            }, 100)
            for (var i = 0; i < 100; i++) {
                i == 99 && resolve()
            }
        }).then(function () {
            setTimeout(function () { // timer4
                console.log(6)
            }, 0)
            console.log(7)
        })

        console.log(8)
    </script>

His execution process is:

1.Add () synchronization task is directly performed, the printing. 1;
2.add () inside setTimeout is asynchronous tasks and macro functions, denoted timer1 macro function into a queue;
3.add () is asynchronous tasks below setTimeout and macro function, denoted timer2 queue into macro function;
4.new Promise synchronization task is directly performed, printing. 4;
5.Promise setTimeout is asynchronous tasks inside and macro functions, denoted timer3 queue into macro function;
6 .Promise inside the for loop, the synchronization task, code execution;
7.Promise.then micro task into the task queue micro;
8.console.log (8) is synchronized task, direct execution, printing 8;
9. At this time the main thread task is completed, the micro-check job queue, there Promise.then, micro perform tasks found setTimeout is asynchronous tasks and macro functions, denoted timer4 queue into macro function;
the console.log task queue 10. the micro (7) a synchronization task, perform direct printing 7;
11 micro task is completed, the end of the first cycle;
12. check macrotask Event Table, there timer1, timer2, timer3, timer4, four timers macrotask , according to the set Order to give delay time can be performed, i.e., Event Queue: timer2, timer4, timer3 , timer1, taken in a first row of timer2;
13. Remove timer2 performed, the console.log (3) synchronization task, perform direct printing 3 ;
14. No micro task, the second end of the Event Loop;
15. A timer4 removed performed, the console.log (6) synchronization task, perform direct printing 6;
16 tasks are not fine, the third Event Loop End;
17. Remove timer3 performed, the console.log (5) synchronization task, direct execution, printing 5;
18 tasks are not fine, the end of the fourth Event Loop;
19. timer1 removed performed, console.log (2) synchronization task, direct execution, printing 2;
20. no micro tasks, no task macros, the fifth end Loop the Event;
21. A result: 1,4,8,7,3,6,5,2.
Reference article:
https://www.jianshu.com/p/e06e86ef2595
https://segmentfault.com/a/1190000013662126
http://www.ruanyifeng.com/blog/2014/10/event-loop.html
https://segmentfault.com/a/1190000012925872
 

Guess you like

Origin www.cnblogs.com/tutuj/p/11025042.html