WEB front end-performance optimization

Performance optimization

1. For front-end personnel

2. Mainstream, for Chrome,

3. Miscellaneous, summary

Optimization: md

The function and composition of the browser

Network: The browser downloads various resources through the network module, such as html text; javascript code; style sheet; pictures; audio and video files, etc. The network part is particularly important because it takes a long time and requires secure access to resources on the Internet.

Resource management: The resources downloaded from the network or obtained locally need to have an efficient mechanism to manage them. For example, how to avoid repeated downloads, how to cache resources, etc.

Web browsing: This is the core and most basic function of the browser, the most important function. How to turn resources into visual results.

Multi-page management:

Plug-in and management:

Account synchronization

Security Mechanism

Developer tools

The browser's kernel (rendering engine)

There is one of the most important modules in the browser. Its main function is to turn all requested resources into visual images.
This module is the browser kernel, usually it is also called the rendering engine.
Browser kernel summary:

IE---------->Trident

Safari------>WebKit
WebKit itself is mainly composed of two small engines,
one is the rendering engine "WebCore", and the
other is the javascript interpretation engine "JSCore",
both of which are derived from KDE's rendering engine KHTML And javascript interpretation engine KJS is derived.

Chrome ------> WebKit branch engine -----> Blink
in 13 years released version of Chrome 28.0.1469.0 start, Chrome abandon Chromium engine revolutions
and using the latest Blink engine (based on Apple's WebKit2-- The new WebKit engine launched in 2010).
Compared with the previous generation engine, Blink streamlines the code, improves the DOM framework, and also improves security.

Opera's
old version of Opera 4 to 6 versions: Elektra typesetting engine
Opera7.0: Presto rendering engine
Opera announced in February 2013 that it would abandon Presto:
use the Chromium engine;
it has been converted to the Blink engine;

Firefox------>Gecko

Process and thread

Process: Once a program is executed, it occupies a unique memory space and is the basic unit of operating system execution.

​ There is at least one running thread in a process: the main thread, which is automatically created after the process is started.

​ A process can also run multiple threads, we say that the program is running in multiple threads.

​ Data in a process can be shared by multiple threads, and data between multiple processes cannot be shared.

Thread: It is an independent execution unit within a process, and is the smallest unit of CPU scheduling. The basic unit of program operation.

​ Thread pool: A container that holds multiple thread objects to realize the repeated use of thread objects.

The JS engine runs in a single thread!

Modern browsers: multi-process, multi-threaded model

1. Unbearable past:
When you open many pages through the browser, if one of the pages becomes unresponsive or crashes,
then more unfortunate things will follow, and all the pages you open will get If there is no response, the
most unbearable thing is that some of the pages may also contain unsaved or unsent information

2. How do browser manufacturers solve it?
Using a multi-process model, the model can bring benefits
①. Avoid the stability of the entire browser due to unresponsive or crashing of a single page
②. When a third-party plug-in crashes, it will not affect the stability of the entire browser
③ .Safety

3. What processes are in the browser
①.
Browser process: the main process of the browser, responsible for the display of the browser interface, and the management of each page,
the ancestor of all other types of processes in the browser, responsible for the creation and destruction of other processes
It has one and only one!!!
②.
Render process: web page rendering process, responsible for the rendering of the page, there can be multiple, of
course, the number of rendering processes is not necessarily equal to the number of web pages you open
③. Various plug-in processes
④ GPU process
The browsers of mobile devices may be different:
Android does not support plug-ins, so there is no plug-in process. The
GPU has evolved into a thread of the Browser process. The
Renderer process has evolved into a service process of the operating system, which is still independent.

4. There are many threads inside each process
. The purpose of multithreading is to keep the user interface highly responsive.
For example: in order to prevent the UI thread of the Browser process from being affected by other time-consuming operations (loading of large files, reading and writing of local files) Blocking,
then we put these operations in the sub-thread to deal with.
In the Renderer process, in order not to allow other operations to block the high-speed execution of the rendering thread, we usually [pipeline] the rendering process,
using the computer's multi-core advantages to allow different stages of rendering to be executed in different threads (the rendering thread cannot slow)

Browser's rendering engine

Main module

  • A rendering engine mainly includes: HTML parser, CSS parser, javascript engine, layout module, drawing module

    • HTML parser: A parser that interprets HTML documents. Its main function is to interpret HTML text into a DOM tree.
    • CSS parser: its role is to calculate style information for each element object in the DOM and provide infrastructure for layout
    • Javascript engine: Use Javascript code to modify the content of the webpage and also modify the css information. The javascript engine can interpret the javascript code and modify the content and style information of the webpage through the DOM interface and the CSS tree interface, thereby changing the rendering result.
    • Layout (layout): After the DOM is created, Webkit needs to combine the same type information of the element objects in it, calculate their size and position and other layout information, to form an internal representation model that can express all this information
    • Drawing module (paint): use the graphics library to draw the nodes of each webpage after the layout calculation into image results

    Remarks: Document Object Model (DOM)

Rough rendering process

  • The whole process of the browser rendering the page: the browser will parse the document from top to bottom.
    1. When encountering HTML tags , call the HTML parser font to parse the corresponding tokens (a token is the serialization of a label text) and build a DOM tree (that is, a piece of memory, which stores tokens and establishes the relationship between them).
    2. When the style/link tag is encountered, the corresponding parser is called to process the CSS tag and build a CSS style tree .
    3. When encountering script tags, call javascript engine to process script tags, bind events, modify DOM tree/CSS tree, etc.
    4. Combine the DOM tree and the CSS tree into a render tree .
    5. Render according to the render tree to calculate the geometric information of each node (this process needs to rely on the GPU).
    6. Finally, each node is drawn on the screen.

The above modules rely on many other basic modules, including network storage 2D/3D image audio video decoder and picture decoder.
So the rendering engine will also include how to use these dependent modules.

Two, blocking rendering

1. About css blocking:

Disclaimer: Only external css introduced by link can cause blocking.
1. The style in the style tag :
(1). It is parsed by the html parser;
(2). Does not block browser rendering (may produce "flash screen phenomenon");
(3). Does not block DOM parsing;

2. External css style introduced by link (recommended method) :
(1). It is parsed by CSS parser. Synchronous analysis
(2). Block browser rendering (this blocking can be used to avoid "flash screen phenomenon").
(3). Block the execution of the following js statements (JS and CSS can be styled)
(4). Do not block DOM parsing (the way most browsers work):

3. Optimize the core concept: improve the loading speed of external css as quickly as possible
(1). Use CDN nodes to accelerate external resources.
(2). Compress css (using packaging tools, such as webpack, gulp, etc.).
(3). Reduce the number of http requests and merge multiple css files.
(4). Optimize the code of the style sheet

2. About js blocking:

​ 1. Block subsequent DOM parsing :
​ Reason: The browser does not know the content of the subsequent script. If the following DOM is parsed first, and the subsequent js deletes all the subsequent DOM,
the browser will do useless work, browsing The browser can’t predict what specific operations are done in the script. For example, operations like document.write
​ simply stop. After the script is executed, the browser continues to parse the DOM downwards.
​ 2. Block page rendering :
​ Reason: JS can also set styles for the DOM, the browser waits for the script to be executed, and renders a final result, avoiding useless work.
3. blocking the implementation of the follow-up js :
reasons: to maintain dependencies, such as: the introduction of jQuery must be reintroduced bootstrap

3. Remarks

​ [Note 1]: CSS parsing and js execution are mutually exclusive (mutually exclusive), js stops executing when css is parsed, and css stops parsing when js is executed.

[Note 2]: Whether blocking css, js or blocked, will not clog the browser to load external assets (images, video, style, script, etc.)
reasons: always in a browser: "Put the request is made to" work Mode, as long as it involves the content of the network request,
whether it is: pictures, styles, scripts, it will first send a request to obtain resources. As for when the resources are used locally, the
browser itself coordinates. This approach is very efficient.

[Note 3]: Both WebKit and Firefox have performed the [pre-analysis] optimization. When executing the js script, other threads of the browser will pre-parse the rest of the document, find and load other resources that need to be loaded over the network. In this way, resources can be loaded on parallel connections,
thereby increasing the overall speed. Please note that the pre-parser does not modify the DOM tree

In the above process, the "DOMContentLoaded" and "onload" events will be triggered during the loading and rendering of the web page
, respectively, after the DOM tree is constructed (parsed), and after the DOM tree is constructed and the resources that the web page depends on are loaded.

  • The above is a complete rendering process, but many modern web pages are dynamic, which means that after the rendering is completed, the
    browser has been repeatedly executing the rendering process due to the animation of the web page or user interaction . (Redraw and rearrange). The above numbers indicate the basic order, which is not strictly consistent.
    This process may be repeated or intersected.

Different browsers have different CSS parsers.

The browser finds the server for something

Receive Response: The "response header" of the received data, the status code

Receive Data: The real data is being transmitted.

Style rendering

Asynchronous analysis: non-blocking. (More efficient)-callback

Synchronous analysis: blocking.

1. The style in the Style tag is parsed by the HTML parser.

2. The internal style written in the page style tag is parsed asynchronously (prone to flash screen phenomenon)

3. The browser loads resources [asynchronous]

Link external CSS rendering

Browser access to resources is asynchronous.

1. The styles that the link comes in are parsed by parse Stylesheet (CSS) and are parsed synchronously.

2. The css parser will block the rendering of the page. (The external style that the link comes in will block page rendering and avoid splash screen)

3. It is recommended to use link

CSS layers

Layout: Layout----Arrangement---------Rearrangement (rearrangement/reflow)

Paint: drawing----drawing--------repainting (repainting)

When the browser renders a page, it divides the page into many layers, with large and small layers, and each layer has one or more nodes.

Conditions for layer creation

​ The Chrome browser will create a layer when any of the following conditions is met:

  1. Have CSS properties with 3D transforms (translateZ)

  2. Use accelerated video decoding node ------ with video tag

  3. There are nodes

  4. CSS3 animation nodes

  5. Elements with CSS acceleration attributes (will-change will change)

When rendering the DOM, what the browser does is actually:

	1. 获取DOM后分割为多个图层
    	2. 对每个图层的节点计算样式结果		(Recalculate style--样式重计算)
        3. <font color=red>为每个节点生成图形和位置	</font>		(Layout--布局,重排,回流)
        4. <font color=red>将每个节点绘制填充到图层位图中	</font>	(Paint--重绘)
        5. <font color=red>图层作为纹理上传至GPU</font>
        6. 组合多个图层到页面上生成最终屏幕图像	(Composite Layers--图层重组)

Repaint

Redrawing is a browser behavior triggered by a change in the appearance of an element, such as changing attributes such as outline and background color. The browser will redraw according to the new attributes of
the element to give the element a new appearance. Redrawing does not bring about re-layout, so it does not necessarily accompany re-arrangement.

It should be noted that the redrawing and rearrangement are all based on the layer. If an element in the layer needs to be redrawn, then the entire layer needs to be redrawn.
So in order to improve performance, we should let these "changing things" have their own layers,
but fortunately, most browsers will automatically create layers for CSS3 animation nodes.

Rearrangement (Reflow also known as: reflow)

When the render object is created and added to the render tree, it does not contain position and size information. The process of calculating these values ​​is called layout or rearrangement

"Redrawing" does not necessarily require "rearrangement". For example, changing the color of a webpage element will only trigger "redrawing" and not "rearrangement" because the layout has not changed.
"Reflow" will lead to "redraw" in most cases. For example, changing the position of a web page element will trigger both "reflow" and "redraw" because the layout changes.

The attribute that triggers the redraw

  • color * background * outline-color
    rder-style * background-image * outline
    • border-radius * background-position * outline-style
      sibility * background-repeat * outline-width
      • text-decoration * background-size * box-shadow

Attributes that trigger rearrangement (reflow)

  • width * top * text-align
    ight * bottom * overflow-y
    • padding * left * font-weight
      rgin * right * overflow
      • display * position * font-family
        rder-width * float * line-height
        • border * clear * vertival-align
          n-height * white-space

(Key) Common rearrangement operations

The cost of Reflow (rearrangement) is much higher than the cost of Repaint (repaint).
The Reflow of a node is likely to lead to the Reflow of the child node, or even the parent node and nodes of the same level.
It may not be much on some high-performance computers, but if Reflow happens on a mobile phone, the process is very painful and power-consuming.
(Games developed with H5 generate heat on the mobile terminal and consume serious power)

Therefore, the following actions are likely to be relatively expensive.
1. When you add, delete, or modify DOM nodes, it will cause Reflow and Repaint.
2. When you move the position of the DOM
3. When you modify the CSS style.
4. When you Resize the window (zoom in and reduce the window) (the mobile terminal does not have this problem, because the zoom of the mobile terminal does not affect the layout viewport)
5. When you modify the default font of the web page.
[When getting some attributes (width, height...)! ! ! ! !
Note: display:none (non-occupied hidden) will trigger reflow, and visibility:hidden (occupied hidden) will only trigger repaint, because there is no position change.

Optimized scheme for redrawing and rearranging

We know that the browser has gone through the following "detailed" steps when rendering the page:

	1. 计算需要被加载到节点上的样式结果(Recalculate style--样式重计算)*
	2. 为每个节点生成图形和位置(Layout--重排或回流)
	3. 将每个节点填充到图层中(Paint--重绘)
	4. 组合图层到页面上(Composite Layers--图层重组)
   如果我们需要提升性能,需要做的就是减少浏览器在运行时所需要做的工作,即:尽量减少1234步。

[The specific optimization scheme is as follows]:
1. Try to use CSS3 transform to replace top left and other operations when transforming element position. Transform
and opacity changes only affect the combination of layers

2. Usage opacity instead visibility] (1) The use of visibility does not trigger the rearrangement, but still redrawn. (2) directly using an opacity that is triggered redraw, and trigger rearrangement (GPU designed from the ground so!). (. 3). Opacity layer with use, i.e., it does not trigger the trigger does not redraw rearrangement . (opacity with the will-change) Reason: When changing transparency, before simply reduce GPU when the painting was already good texture alpha values to achieve the desired effect, we do not need a whole redrawn. But this premise is this opacity is modified itself must be a layer. ​ 3. [Do not use table layout]​ table-cell​ 4. Combine [multiple operations of changing style attributes into one] operation​ Do not modify the style of the DOM one by one, define the class in advance, and then modify the className of the DOM​ 5. [Modify the DOM after offline ()] Since the element whose display attribute is none is not in the render tree, operations on hidden elements will not cause other elements to be rearranged. ​ If you want to perform complex operations on an element, you can hide it first, and then display it after the operation is complete. This only triggers 2 rearrangements when hidden and displayed. ​ 6. [Using document Fragment] (documentFragment)------Vue uses this method to improve performance.














​ 7. [Do not put the attribute values ​​of certain DOM nodes in a loop as a loop variable]
​ When you request some style information from the browser, the browser will flush the queue, such as:

​ 1.offsetTop, offsetLeft, offsetWidth, offsetHeight

​ 2.scrollTop/Left/Width/Height

​ 3.clientTop/Left/Width/Height

​ 4.width, height
​ When you request some of the above attributes, the browser needs to refresh the internal queue in order to give you the most accurate value,
because there may be operations in the queue that affect these values. Even if you get the layout and style information of an element that has nothing to do with the layout information that has recently occurred or changed, the browser will forcibly refresh the rendering queue.
8. In the process of animation implementation, enable GPU hardware acceleration: transform: tranlateZ(0)
9. Create a new layer for animation elements to increase the z-index of animation elements
10. When writing animations, try to use the following APIrequestAnimationFrame----request Animation frame

requestAnimationFrame----request animation frame

1.window.requestAnimationFrame()
Description: This method will tell the browser to call the function you specify before the next redraw and rearrangement
. 1. Parameters: This method uses a callback function as a parameter, and this callback function will be in the browser next time Called before redrawing.
The callback function will be automatically passed in a parameter, DOMHighResTimeStamp, which identifies the current time when requestAnimationFrame() starts to trigger the callback function

​ 2. Return value:
​ A long integer, request ID, which is the only identifier in the callback list. It is a non-zero value and has no other meaning. You can pass this value to window.cancelAnimationFrame() to cancel the callback function. Note: If you want to continue to update the next frame animation before the next redraw browser, then the callback function itself must be called again window.requestAnimationFrame ()

2. window.cancelAnimationFrame(requestID)
cancels an animation frame request previously added to the plan by calling the window.requestAnimationFrame() method.
requestID is the value returned when the window.requestAnimationFrame() method is previously called. It is a time identifier, and its usage is similar to the id of a timer.

CDN

CDN fast

[External link image transfer failed. The origin site may have an anti-leech link mechanism. It is recommended to save the image and upload it directly (img-Guch56JJ-1604846375736) (F:\WEB\WEB\009-git,svn,modularization, optimization\009 -git,svn,modularization, optimization\performance optimization_stu\icon\01_web front-end and back-end overall icon.png)]

What is CDN? How does it work?

The website usually puts all its servers in the same place. When the user base increases, the company must deploy content on multiple geographically different servers.
In order to shorten the time of http requests, we should place a large number of static resources. Get closer to the user.

Content Delivery Networks CDN (Content Delivery Networks)
CDN is a group of web servers distributed in many different geographical locations, used to distribute content to users more effectively

The basic idea:
try to avoid bottlenecks and links on the Internet that may affect the speed and stability of data transmission, so that content transmission can be faster and more stable.
By placing node servers in various places in the network constituted by a layer of intelligent virtual network on the basis of the existing Internet, the
CDN system can be based on the network traffic and the connection of each node, load status, distance to users and response time in real time Such comprehensive information
redirects the user's request to the service node closest to the user.

Infrastructure: The simplest CDN network consists of a DNS server and several cache servers.
1. The url entered by the user will be "translated" into the corresponding ip address through DNS resolution, so as to find the CDN dedicated server.
2. The CDN "gets" the user's IP address, and then cooperates with the regional load balancing device to select a regional load balancing device in the area to which the user belongs, and tell the user to initiate a request to this device.
3. The "choice" basis in the above steps
(1). The basis for selection includes: judging which server is closest to the user according to the user's IP address;
(2). judging according to the content name carried in the URL requested by the user Which server has the content required by the user;
(3). Query the current load situation of each server and determine which server still has the service capacity.

Guess you like

Origin blog.csdn.net/rraxx/article/details/109566496