1. Browser rendering process
Common rendering engines
- Its: Safari
- Blink (Webkit fork) : Chromium/Chrome Opera, Microsoft Edge
- Gecko: FireFox
- Trident: IE, Edge (old)
Rendering engine: Capable of converting HTML/CSS/JavaScript text and resource files into image results
Chrome architecture
Multiprocess browser
- Browser: Address columns, bookmarks, web requests, file access, etc
- Renderer: Responsible for displaying all the contents of the site’s tabs
- Plugin: Controls all the plugins used by the site
- GPU: A GPU processing task independent of other processes, with only one GPU process (processing requests from multiple programs and drawing them on a single page)
Renderer process
- The renderer process is responsible for everything that happens inside the TAB, and the main thread handles most of the code in the renderer process
- The Webwork or service worker starts another thread (to solve task queue congestion)
Rendering process: Parsing part
- Build a DOM tree
- Subresource loading (JavaScript can organize parsing)
- Prompt browser how to load resources
- Style sheet calculation
- Layout, Layout
- Paint, Paint
Rendering process: Compositing part
-
Convert document structure, element styles, geometry and drawing order into pixels on the screen (rasterization for short)
-
Composition is the layering, rasterizing, and finally combining of the parts of a page in a synthesizer thread
- Take the DOM and split it into layers
- Bitmap each layer independently
- Upload layers to GPU as textures
- Compound multiple layers to produce the final screen image
Rendering process: GPU rendering
- After the DOM tree is created to determine the drawing order (Layer), the main thread hands the rendering information to the synthesizer thread, which rasterizes the layers and splits them into blocks. The raster thread rasterizes each block and stores it in the GPU
- The synthesizer process sends synthesizer frames to the browser process via IPC (inter-component communication). The UI process is called to make changes to the browser UI using synthesizer frames, which are then sent to the GPU for on-screen display. (Screen sliding creates another synthesizer frame to send to GPU)
- Compositing is done under the GPU thread and does not involve the main thread, so the layout and drawing are not changed after the DOM tree is established, and using compositing animation improves performance.
Layering mechanism: a web page is displayed by multiple layers, and then combine these layers into one layer. When DOM or style changes, GPU(graphics card) can cache some unchanged content (layer), and then combine the layer to be changed with the cache layer to improve rendering efficiency. Therefore, let GPU participate in animation to improve animation performance
Layer model:
- The browser generates Layers for elements based on the CSS properties
- Upload Layers as a bitmap to GPU
- When changing Layer transform, OpCity, etc., rendering will skip Layout and paint and directly inform GPU to transform Layer
Deep understanding of rearrangement and redrawing
Rearrangement: When a DOM change affects an element’s geometry (width or height), the browser needs to recalculate the element’s geometry, as well as the geometry and position of other elements. The browser invalidates the affected portion of the render tree and reconstructs the render tree. This process is called rearrangement.
Redraw: After the rearrangement is complete, redraw the affected parts to the screen, a process called redraw.
Both rearrangement and redrawing will involve the main thread in the Layer rendering of the image, affecting the performance of the browser.
We need to rearrange and redraw as little as possible.
- The simpler the stylesheet, the faster it can be rearranged and redrawn
- The higher the DOM hierarchy rearranged and redrawn, the higher the rendering cost
- Table elements cost more to rearrange and redraw than div elements
- Separate read and write operations as much as possible
- Styles take the form of themes that change uniformly
- Cache reordering results
- Offline DOM Fragment and virtual DOM Fragment
- Invisible elements do not affect rearrangement redraw (display: none)
2. Understand parsing rendering and code optimization
To speed up web page loading and improve user experience, you need to get important elements on the screen as quickly as possible on the first load. Instead of waiting until all the elements are ready to display, the following illustration illustrates the difference between the two approaches.
Critical Rendering Path
Key render path: Refers to the browser’s process from requesting HTML, CSS, JavaScript files to rendering to the screen.
-
Build the DOM tree: This process is gradual, assuming that the HTML file is large, and that a round-trip Time (RTT) only gets a portion of it, the browser will start building the DOM once it gets that portion, rather than waiting for the entire document to be ready for rendering.
- Parse HTML into many Tokens
- Tokens become objects
- Group objects into a DOM tree
-
Build CSSOM: Parsing can take place at the same time as building the DOM, but CSSOM must wait until all the bytes are received before building.
- Parse the CSS file and build a CSSOM tree
-
Build the Render Tree: The browser uses DOM and CSSOM to build the Render Tree. Instead of building all the nodes as you would a DOM, the browser builds only what needs to be displayed on the screen. (Head, meta, etc., are not displayed) — corresponds to the Layout procedure in Dev Tools
- Build with DOM and CSSOM
-
Layout: Calculates the position and size of elements
-
Paint: Convert render Tree to pixels for display on screen. Dev Tool Performance Panel Paint process
Note: not in sequence, there will be some crossover
The introduction of JavaScript
Because JavaScript affects the critical path rendering queue; Put the script tag as far back as possible
-
JavaScript is blocked when parsing HTML to build the DOM
-
JavaScript execution is blocked by the CSSOM build, which means that JavaScript cannot be executed until the CSSOM build is complete
-
If an asynchronous script is used, the network request of the script takes a lower priority and does not block THE DOM build during the network request and does not start executing the script until the request completes.
Asynchronous script
Asynchronous script
Browser composition layer and page optimization
filter: blur(100px);
Copy the code
This line of CSS is used to implement a Gaussian blur, which can be difficult for browsers to render when multiple elements have this property; As a result, the CPU usage of the rendering process is too high, resulting in stalling.
will-change: transform;
Copy the code
The principle is actually very simple, this line of code can enable GPU accelerated page rendering, thus greatly reducing the CPU load pressure, to achieve the purpose of optimizing page rendering performance.
The browser’s rendering flow
In addition to the steps of obtaining network resources, we understand the display of Web pages, generally can be divided into building DOM tree, building rendering tree, layout, rendering, rendering layer synthesis several steps.
- Build A DOM tree: The browser parses HTML into a tree-like DOM tree, which occurs when the page is first loaded or when the structure of the element node is modified.
- Build a render tree: The browser parses the CSS into a tree-like CSSOM tree and merges it with the DOM tree to create a render tree.
- Layout: The browser calculates the position of each node on the screen based on the nodes in the rendering tree and their corresponding CSS styles. When an element’s position or size changes, it causes a chain reaction of other nodes to rearrange, a process known as Reflow.
- Paint: Traverses the render tree, calling the renderer’s method (Paint ()) to draw the node content — pixel fill. This process occurs when local repainting is caused by backflow or other CSS changes that do not affect the layout. This is called Repaint.
- Composite: Multiple rendered layers are combined according to the hierarchical style of CSS to produce a bitmap, which is displayed on the screen via a graphics card.
How browsers render
According to the above rendering process, the transformation principle of DOM tree to screen display is essentially the evolution of tree structure to layer structure.
-
RenderObject — RenderObject
Each node corresponds to a render object, which is combined to maintain the tree structure of the DOM tree. The render object draws the DOM node through a drawing context (GraphicsContext) that calls the corresponding method
-
– RenderLayer rendering layer
In the first layer model during rendering, objects in the same Z-axis coordinates will be rendered in the same rendering layer, forming different rendering layers to represent their hierarchical relationships according to different hierarchical contexts.
Browsers automatically create new layers for rendered objects that meet the conditions for forming a cascading context. Common situations that can cause browsers to create new layers for them include the following:
- The root document
- Have clear positioning attributes (relative, fixed, sticky, absolute)
- opacity < 1
- It has the CSS fliter property
- The CSS mask property is available
- Has the CSS mix-blending-mode property and the value is not normal
- Has a CSS transform property and is not None
- Backface -visibility property is hidden
- CSS Reflection property
- It has the CSS column-count attribute and the value is not auto or it has the CSS column-width attribute and the value is not auto
-
Currently, animations are applied to opacity, Transform, fliter, and backdrop filter
-
The overflow is not visible
Objects that do not meet these conditions will share the same render layer with the first parent element that has a render layer, so in effect the render object will share the render layer with its subelement.
-
Graphics layer – GraphicsLayer
An important rendering vector and tool, but it does not deal directly with the rendering layer, but with the composition layer.
A layer model that is responsible for generating the content graph that is eventually ready to be rendered and has a graphics context that is responsible for the output of the bitmap of that layer. Bitmaps stored in shared memory will be uploaded to the GPU as textures. Finally, the GPU will synthesize multiple bitmaps and draw them on the screen.
-
Composite layer – CompositingLayer
The rendering layer will be promoted to the synthesis layer if it meets the corresponding conditions. The compositing layer has its own graphics layer, and other non-compositing layers share one with their parent.
Common commission to the synthetic layer:
- Transforms: Translate3D, translateZ, etc
- Video, Canvas, iframe and other elements
- Animation-opacity conversion via element.animate (
- Opacity animation conversion via с SS animation
- position: fixed
- Has the will-change attribute
- Animation or transition is applied to opacity, Transform, fliter and backdropfilter
GPU acceleration can only be enabled if CPU intensive rendering elements are promoted to a new compositing layer
Implicit synthesis
One or more non-composite elements should appear on top of the composite elements in the stack order and be promoted to the composite layer.
- Two elements that are absolutely positioned, because of the z-index difference, will be overwritten
- use
transform: translateZ()
Changing the z-axis of an element so that it overlaps with its sibling elevates the element to the composition layer
Layer explosion:
Too many layers will consume the GPU and a large amount of memory resources, which severely degrades page performance. Therefore, blindly using GPU acceleration may backfire.
Implicit synthesis can occur without overlap, and elimination of implicit synthesis is the elimination of element overlap.
Layer compression:
When multiple render layers overlap with a composite layer, they are compressed into a GraphicsLayer to prevent possible “layer explosions” due to overlapping.
How do browsers view the compositing layer – Chrome Devtools
Optimization Suggestions
1. Animation is implemented by Transform
The reasons for this are:
- If you use left/ Top for position changes, the animation node and Document will be rendered in the same GraphicsLayer, and continuous animation will cause the entire Document to be redrawn constantly
- Transform allows the animation node to be rendered in a separate compositing layer without affecting other layers.
- Animations run entirely on the GPU and tend to be smoother than the CPU processing layers and sending them to the graphics card for display and drawing.
2. Reduce implicit composition
In essence, the purpose is to ensure the correct overlapping order of layers. However, in practical development, implicit composition can easily lead to the generation of some meaningless composition layers. In the final analysis, we are required to restrict our layout habits during development to avoid trashing.
It is not always possible to blindly set z-index to avoid this. Sometimes z-index can also lead to implicit composition. In this case, try to adjust the order of the nodes in the document so that the next node overwrites the first one.
The method is not unique, the specific method or according to the page specific analysis.
3. Reduce the size of the composite layer
.bottom {
width: 100px;
height: 100px;
top: 20px;
left: 20px;
z-index: 3;
background: rosybrown;
}
.top {
width: 10px;
height: 10px;
transform: scale(10);
top: 200px;
left: 200px;
z-index: 5;
background: indianred;
}
Copy the code
Using Chrome Devtools to check the memory usage of the two composite layers, the.bottom is 39.1 KB and the.top is 400 B.
For some solid color layers, we can use the width and height attributes to reduce the physical size of the composite layer, and then transform: Scale (…). Zoom in, which can greatly reduce the memory consumption of layer composition.
Cold knowledge
Window: beforeunload event
The beforeUnload event is triggered when the browser window closes or is refreshed. The current page will not be closed directly, you can click the OK button to close or refresh, or cancel the closure or refresh.
Bubbles | No |
---|---|
Cancelable | Yes |
Interface | Event |
Event handler property | onbeforeunload |
Events enable the web page to trigger a confirmation dialog asking the user if they really want to leave the page. If the user confirms, the browser navigates to the new page, otherwise the navigation is cancelled.
According to the specification, to display the confirmation dialog, the event handler calls preventDefault() on the event.
Note, however, that not all browsers support this method, and some browsers require event handlers to implement one of the two legacy methods instead:
- Assigns a string to the returnValue property of the event
- Returns a string from the event handler.
window.addEventListener('beforeunload', (event) => {
// Cancel the event as stated by the standard.
event.preventDefault();
// Chrome requires returnValue to be set.
event.returnValue = '';
});
Copy the code