From the browser to see the rendering process performance optimization

First, learn the basics under your browser:

1. process (process) and thread (thread)

Process (process) and thread (thread) is the basic concept of the operating system.

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 (is to establish a program running on the basis of unit processes on).

Modern operating systems which can run multiple tasks simultaneously, such as: using the Internet browser at the same time can also listen to music.

For the operating system, a task is a process, such as opening a browser is a browser started the process to open a Word started the process a Word.

Some processes simultaneously to do more than one thing, such as Word, it also can be typing, spell checking, printing and other things. Within a process, to do more things at the same time, we need to run multiple "sub-tasks", we put these "sub-tasks" in the process called threads.

Since each process to do at least one thing, it is a process that at least one thread. The system will allocate a separate memory for each process, so the process has its independent resources. Shared memory space of the process (including code segments, data sets, stack, etc.) between the individual threads within the same process.

To borrow a vivid metaphor, the process is like a border between manufacturers, but like a thread between employees within the plant, can do their own thing their own, can cooperate with each other to do the same thing.

When we start an application, the computer will create a process, the operating system will allocate a portion of memory for the process, the application of all the states will be saved in this memory.

Applications may also create multiple threads to aid work, these threads can share data this part of the memory. If the application is closed, the process will be terminated, the operating system will release the relevant memory.

2. The browser's multi-process architecture

A good program is often divided into several independent and cooperate with each other modules, browser as well.

Example, in Chrome it consists of multiple processes, each process has its own core duties, they complement each other to complete the overall function of the browser,

Each process in turn contains multiple threads, multiple threads within a process would work together with the completion of duty lies process.

Chrome's multi-process architecture, which is the top floor there is another process a Browser process to coordinate browser.

Since the default to open a new tab page to create a new process, a single tab page crash will not affect the entire browser.

Also, third-party plug-in crashes will not affect the entire browser.

Multi-process can take full advantage of modern multi-core CPU.

Easy to use process isolation sandbox model plug-ins, improve the stability of the browser.

The system browser to open the process of allocating memory, CPU and other resources, so the memory and CPU resource consumption will be greater.

But Chrome in memory release does a good job, the basic memory is quickly freed for other programs running.

The main processes and responsibilities 3. Browser

The main process Browser Process

Responsible for display and interaction browser interface. Management of each page, create and destroy other processes. Network resource management, and other downloads.

Third-party plug-in process Plugin Process

Each corresponds to a type of plug-in process, only when using the plug-in creates.

GPU process GPU Process

At most one for 3D rendering, etc.

The rendering process Renderer Process

The rendering process called browser or browser kernel, the interior is multithreaded. Responsible for page rendering, script execution, event handling, and so on. (This article focuses on)

4. The rendering process (browser kernel)

The rendering process is multi-threaded browser, let's look at what are the main threads that are:

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 (the equivalent of being frozen), GUI updates are saved to be executed immediately when the engine idle until the JS in a queue .

2. JS engine thread

  • Javascript engine, also known as JS kernel, handles Javascript script. (Eg V8 engine)
  • 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.
  • Note, 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. Thread clocked flip-flop

  • Legend of the thread where the setInterval and setTimeout
  • 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. http request asynchronous thread

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

The browser rendering process

  1. Parse HTML files, builds a DOM tree, while the main process responsible for downloading the browser CSS file
  2. CSS file download is complete, the CSS file parsed into a tree data structure, and then combined into a DOM tree merge tree RenderObject
  3. RenderObject layout tree (Layout / reflow), responsible RenderObject element in the tree size, position and the like calculated
  4. Draw RenderObject pixel information tree (paint), rendering the page
  5. The main browser process will default layer and a composite layer process to the GPU, GPU then processes the various layers of synthetic (composite), and finally show page

So, a few questions like the following understanding:

1. Why Javascript if the single-threaded?

This is because the Javascript scripting language born of this mission due! JavaScript is user interactive processing page, as well as manipulate the DOM tree, CSS style tree to present the user with a dynamic and rich interactive experiences, and interactive processing server logic.

If JavaScript is multi-threaded approach to the operation of these UI DOM, the UI operation conflict may occur.

If Javascript is multi-threaded, then in interactive multi-threaded, in the UI DOM node may become a critical resource,

Assume there are two threads simultaneously operate a DOM, a charge of a modification responsible for deleting, so this time we need the browser to decide how to implement the results of which thread into effect.

Of course, we can solve the above problems by lock. But in order to avoid the introduction of locks and greater complexity, Javascript initially chose a single-threaded execution.

2. Why JS blocking the page loads?

Because JavaScript is steerable DOM, and if at the same time rendering interface to modify these elements attributes (ie JavaScript 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 and JavaScript engine thread mutually exclusive relationship .

When the JavaScript engine executes the GUI thread is suspended, GUI updates are saved immediately be executed when the thread is idle until the engine in a queue.

From the above we can infer, because the GUI rendering and JavaScript execution thread is the thread mutually exclusive relationship,

When the browser at the time of execution of JavaScript programs, GUI rendering thread will be stored in a queue until JS program execution is completed, it will then execute.

So if JS execution time is too long, this will cause the page to render incoherent, leading to load the page rendering blocked feeling.

3. css load will cause obstruction it?

We can see from the above browser rendering process:

DOM parsing and CSS parsing are two parallel processes, so CSS parsing load without blocking the DOM.

However, since the Render Tree is dependent on the DOM Tree and CSSOM Tree ,

So after he had to wait to CSSOM Tree is built, which is loaded CSS resources (CSS resources or fails to load), to begin rendering.

Therefore, CSS load will block Dom rendering.

Because JavaScript is steerable DOM and css styles, if both rendering the interface to modify these elements attributes (ie JavaScript 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 and JavaScript engine thread mutually exclusive relationship.

Therefore, style sheets can be loaded in the front and back of the finished js execution, so css will block the execution of js behind.

4. What is the CRP, that is the key to rendering path (Critical Rendering Path)? How to optimize?

Critical path is a browser will render HTML CSS JavaScript to convert a series of steps in pixel content presented on the screen going through. That is our top browser rendering process .

To complete the first rendered as soon as possible, we need to minimize the following three variables:

  • The number of critical resources: the first rendering of the page may prevent resources.
  • Critical Path Length: Get the number of round trips or the total time required for all critical resources.
  • Keyword section: to achieve rendering the page for the first time the total number of bytes required, equivalent to the sum of all the key resource transfer file size.

1. Optimize DOM

  • Remove unnecessary code and comments, including spaces, as far as possible to minimize the file.
  • GZIP compressed files can be used.
  • In conjunction with HTTP cache files.

2. Optimize CSSOM

Narrow, compressing and caching equally important focus for CSSOM we mentioned earlier it will prevent page rendering, so we can consider this aspect to optimize.

  • The key elements in reducing the number of CSS
  • When we declare style sheets, please pay close attention to the type of media queries, which greatly affected the performance of CRP.

3. Optimize JavaScript

When the browser encounters a script tag, the parser will prevent continued operation until the building is completed CSSOM, JavaScript will continue to run and complete DOM building process.

  • async: When we add the async attribute in the script tag, the browser encounters this script will continue to resolve DOM mark, but the script will not be discouraged CSSOM, that is, it does not prevent CRP.
  • defer: the difference between async that the script needs to wait until the document parsing (before DOMContentLoaded events) executed, and async script is allowed to run in the background when the document is parsed (both download process does not block the DOM, but execution will).
  • When our script does not modify the DOM or CSSOM, recommended async.
  • Preload - preload & prefetch.
  • DNS pre-resolution - dns-prefetch.

to sum up

Critical resources from the critical path length count section keywords to optimize our CRP.

  • Minimizing the number of key resources: to eliminate them (inline), to postpone their download (defer) or to resolve them asynchronous (async) and so on.
  • Optimize the number of keywords section (reduce, compression) to reduce download time.
  • Optimized order to load the remaining key resources: to make critical resources (CSS) download as soon as possible to reduce the length of CRP.

Original link: https://segmentfault.com/a/1190000021517583

Guess you like

Origin www.cnblogs.com/qlongbg/p/12170448.html