Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to understand web rendering engine and Front-end Optimization

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article introduces the relevant knowledge of "how to understand web rendering engine and front-end optimization". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

As we all know, most WEB pages are rendered by browsers, and the ability of browsers to display pages basically depends on the kernel of the browser, that is, the rendering engine. Today, take the kernel WebKit of the Chrome browser (more specifically, the WebKit branch Blink, hereinafter collectively referred to as WebKit) as an example to get a simple and comprehensive understanding of how the rendering engine displays pages.

The rendering engine of browser and its dependent module

The rendering engine mainly processes WEB resources such as HTML, CSS, pictures, JavaScript and so on, and finally presents the displayed image. The rendering engine mainly includes processors for parsing these resources, such as HTML interpreter, CSS interpreter, layout calculation + drawing tools, JavaScript engine and so on. In order to better render the rendering effect, the rendering engine will also rely on network stack, cache mechanism, drawing tools, hardware acceleration mechanism and so on.

Rendering process of the browser

The rendering process of the browser mainly includes two parts: the web resource loading process and the rendering process.

The above picture gives a general analysis of the whole process of web page rendering. Let's analyze each process in detail one by one according to the flow of data.

1. Domain name resolution DNS

When we type URL into the browser, the browser will first resolve the domain name. In general, it takes about 60-120 ms for a DNS domain name resolution, and 1.5 RTT (round-trip time) for a TCP three-way handshake. The scheme of WebKit is to adopt DNS prefetching technology and TCP pre-connection technology.

DNS prefetching technology uses the existing DNS mechanism to parse the possible network connections in the web page in advance. That is, to resolve the domain name or IP address of these links with less CPU and network bandwidth when the user browses the web page; when the user clicks the link, it will save time ~ especially when the domain name resolution is slow ~

Similarly, when you enter a link in the address bar, the candidate is silently prefetched by DNS. After DNS prefetching, a TCP connection is established in advance.

Recommendations for this front-end optimization:

Specify the prefetch domain name on the page:

Big data analysis, speculate that users may click on the link, pre-fetched in advance.

By reducing the number of domain names on the page, you can directly reduce the number of DNS requests.

II. SPDY and HTTP2

Because of the 1.5 RTT delay of the TCP three-way handshake caused by the request, Google introduced SPDY to try to solve the delay and security of HTTP (HTTP plaintext). However, after SPDY promoted the birth of HTTP2.0, it no longer updated itself and gradually withdrew.

SPDY is based on SSL and is easily compatible with old and new versions of HTTP. Its advantages are as follows:

Multiplexing. A TCP connection transmits multiple resources. Reduce the cost of TCP connection.

Different resources, different priorities. For example, give priority to loading the first screen.

Header header compression. Reduce the number of bytes transferred. The compression ratio of SPDY to Header can be up to 80%.

SPDY has opened up a new situation in HTTP, killing us too much front-end optimization work, which essentially improves the page loading speed. However, our front-end optimization work can not be neglected. To continue to reduce the number of requests and reduce the number of TCP connections established, let's continue.

Merge resources, such as combo merge JavaScript files, CSS files, use sprite to merge pictures, picture maps, etc.

When the page resource is small, it can be put directly in the page. For example, the small image can be introduced using Base64 coding format. Even some basic styles, or first screen dependent styles, can be placed on the page.

Resource compression technology. Such as Gzip, etc. Mainly the compression of response data.

Streamline JavaScript and CSS code. Reduce useless spaces. Compression confusion ~

Avoid link redirection and avoid incorrect link requests. Establishing multiple links and multiple DNS parsing hinders the DNS prefetching technology. Update the worthless links on your page in time.

III. Resource loading

After the domain name is resolved and the TCP connection is established, the resource loader begins to work.

Resources and resource loaders

Resources include: HTML, JavaScript, CSS stylesheets, pictures, SVG, font files, video and audio, etc. There are three types of resource loaders:

A specific loader, only one type is loaded. Such as the ImageLoader class.

The resource loader for the caching mechanism. A specific loader uses it to find out whether there is a cache resource, a document object that belongs to HTML.

General-purpose resource loader. Used when WebKit needs to obtain resources from the network or file system. It is only responsible for obtaining the data of resources and is shared by all specific resource loaders.

The process of loading resources

In WebKit, resources are based on CachedResource and prefixed with Cached, which reflects the caching mechanism of browsers. That is, when requesting a resource, the browser will see if the resource is in the cache before deciding whether to make a request to the server.

This raises two questions. First, the lifecycle of cached resources.

The browser cache will not increase, and the data in the cache pool will inevitably be replaced. WebKit uses LRU to update the cache pool data at least recently. WebKit follows the HTTP protocol and determines whether the resource is in the resource pool when the page is refreshed. If it exists, some local information of the resource (such as modification time, etc.) is attached, and a HTTP request is sent to the server, and the server makes a judgment according to the information. If the resource is not updated, the network status is 304, making use of the existing resources; otherwise, the resource loading process is performed.

Secondly, the resource loading process.

When the resource is not available in the resource pool, the loading process is performed. WebKit can download common resources and JavaScript resources in parallel (multithreaded). When the current main thread is blocked, WebKit will start another thread to traverse the subsequent web page, collect the required resources and URL to resend the request to avoid blocking.

Based on resource loading, front-end optimization recommendations:

Using the caching mechanism, you can cache resources that are commonly used and will not change in a short period of time, or set the expiration time for resources.

For example, set up ETag/Last-Modified and Expires/Cache-Control.

Expires/Cache-Control works in the same way, indicating the validity period of the resource. If the local cache is still within the validity period, the browser directly uses the local cache and no longer sends requests. When both are configured at the same time, Cache-Control is higher than Expires.

After configuring ETag/Last-Modified, when the browser accesses the URL again, it will send a request to the server to confirm whether the file has been modified. If the file has not been modified, the server will return 304, and the browser will directly obtain the data from the local cache; after modification, the server will return the data to the browser. If both are configured at the same time, the server will first detect ETag before continuing to detect Last-Modified. If both are configured at the same time, the server can more accurately judge whether the browser already has the necessary cached data.

When both ETag/Last-Modified and Expires/Cache-Control pairs are set, Expires/Cache-Control has a higher priority. Therefore, as long as the local cache is valid, the request will not be sent. However, when the page F5 is refreshed and strongly brushed, the cache will become invalid.

Since the resource download may be blocked, place the JavaScript file at the bottom of the page. The JavaScript resource is the one that blocks the main thread, and it takes time to rebuild a thread, so throw the JavaScript away, but the JavaScript resource does not affect the loading of the previous resource and the construction of the DOM tree.

Fourth, the construction from URL to DOM tree.

When we get the resources needed for the page, the rendering engine launches the HTML interpreter to parse the acquired resources. The web page code (byte stream) is decoded by the lexical analyzer, then interpreted into the word Token by the parser, and constructed into a node Node, until finally a DOM tree is built.

During this period, when the node is a JavaScript node, the JavaScript engine will be started, which will block the construction of the DOM tree. Because during JavaScript execution, JavaScript is likely to read and write to the DOM tree. The construction of the DOM tree will not resume until the JavaScript execution is complete.

Other resources do not affect the construction of the DOM tree.

In front-end optimization, it is recommended to put the CSS file at the top of the page in order to build the DOM tree; while the JavaScript file should be placed at the bottom of the page as far as possible to prevent blocking the construction of the DOM tree; and in the onload event of JavaScript, do not write too much JavaScript code that affects the first screen rendering and manipulates the DOM tree.

In addition, let me emphasize:

DOMContentLoaded: the DOM tree has been built

Onload event of DOM: the DOM tree has been built and all the dependent resources of the web page have been loaded ~

Fifth, the process of web page typesetting: from DOM tree to building RenderLayer tree

This process is like the typesetting process of a page. It typesets the DOM tree through the CSS style information to form the RenderObject tree and the RenderLayer tree.

After the DOM tree is built, WebKit builds the RenderObject object for the DOM tree node. WebKit calculates style information such as the location and size of nodes (that is, layout calculation or typesetting) based on the box model, and saves this information to the corresponding RenderObject object.

1. CSS interpreter

The process of CSS interpretation is a process in which CSS strings are processed by CSS interpreters (CSSParser, CSSGrammer) to be represented by internal style rules of the rendering engine. Style rules are the output structure of the interpreter and the input data for style matching.

Specific process: when WebKit renders the element, the CSS interpreter gets the style information and returns the matching result style information. Each element may need to match rules from different sources, followed by a user agent (browser) rule set, a user rule set, and a custom rule set contained in the HTML page. The matching methods of the three are similar.

For each rule set, first look for ID rules, check for matching rules, and then check type rules, label rules, and so on. The matching rules are saved in the matching results. WebKit sorts these rules. For the style attributes required by the element, WebKit selects from the high priority rules and returns the style attribute values.

two。 Rendering basics: RenderObject Tr

After layout calculation and CSS parse, the DOM tree stores the style information in the RenderObject object and constructs the RenderObject tree. At the same time, WebKit creates a RenderLayer tree based on the hierarchical structure of the web page to complete the drawing context. The DOM tree, Render tree, and drawing context coexist until the page is destroyed.

RenderObject tree, a new tree based on DOM tree, is the infrastructure for mechanisms such as layout computing and rendering.

The time when the DOM node creates a new RenderObject object:

The Document node of the DOM tree.

Visual nodes of the DOM tree, such as html, body, div, and so on. Non-visual nodes such as meta, head, script, etc., are not created.

To satisfy WebKit processing, an anonymous RenderObject node needs to be established, which does not correspond to any node of the DOM tree. For example: anonymous RenderBlock node.

Each node object of the DOM tree recursively checks whether the RenderObject needs to be created and creates a RenderObject node according to the DOM node type; the DOM element that is added dynamically creates the RenderObject node accordingly. All these nodes form a RenderObject tree.

3. Rendering basics: Web page hierarchy and RenderLayer tree

On the HTML page, the page is displayed in layers. There are two purposes: 1. Facilitate the development of web pages, set the level of web pages; 2. Simplify the logic of WebKit rendering.

Based on the RenderObject tree, WebKit creates new RenderLayer nodes for some of these nodes as needed, and forms a RenderLayer tree.

The time when the RenderObject node creates a new RenderLayer object:

The RenderView node corresponding to the Document node of the DOM tree.

A child of the Document of the DOM tree, that is, the RenderBlock node corresponding to the HTML node.

Explicitly specifies the RenderObject node of the CSS location.

RenderObject node with transparent effect.

Nodes have RenderObject nodes with effects such as overflow overflow, alpha, or reflection.

RenderObject nodes using Canvas 2D, 3D (WebGL) technology.

The RenderObject node corresponding to the Video node.

The use of RenderLayer nodes can effectively reduce the complexity of web page structure, and in many cases can reduce the cost of re-rendering.

4. Layout calculation and redrawing timing

The CSS box model is the basis of layout calculation; the rendering engine is used to determine how to typeset elements and the positional relationships between elements.

Layout calculation, which is aimed at the calculation of RenderObject tree and its subtrees, is a kind of recursive calculation, and its node information needs to calculate the location and size of its child nodes. The RenderObject object stores the results of the calculation and waits for the rendering time.

Each element implements its own layout.

If the page element defines the width and height, the element is resized according to the custom width and height.

Inline elements such as text nodes need to be combined with font size and text to determine width and height.

The width and height determined by the page element exceeds the width and height provided by the layout container containing blocks, while overflow provides scroll bars for visible or auto,WebKit to ensure that everything is displayed.

In general, the width and height of page elements are calculated at the time of layout. Unless the page defines the width and height of the page element.

Redraw timing: recalculate whenever the style changes.

* Open the page, the browser sets the visual area of the page, and calls the method of calculating the layout. When the visual area changes, the size of the page's containing block also changes, and WebKit needs to recalculate the layout.

The animation of the web page triggers the layout calculation. Animation may change style attributes.

JavaScript modifies the style directly through CSSOM (CSS object Model), which triggers WebKit to recalculate the layout.

User interactions, such as scrolling web pages.

The front-end optimization suggests that because the layout calculation is time-consuming, WebKit requires subsequent redrawing operations once the layout changes. SO, reduce the change of style ~ reduce redrawing ~ make use of the new features of CSS3 (such as CSS3 deformation translate, scale, rotate, transition transition, etc.) can effectively improve the rendering efficiency of web pages.

VI. Web page rendering process: from the RenderLayer tree to the final image

In the previous process, the web page completed the layout calculation and typesetting from DOM tree to RenderLayer tree. Next, the rendering engine (usually drawing tools) completes the drawing of the RenderLayer tree, and finally forms an image to show to the user.

1. Drawing context

Drawing context in which all drawing operations are carried out. It is a platform-independent abstract class that bridges each drawing operation to a different drawing concrete implementation class.

2D drawing context:

Provides the drawing interface of the basic drawing unit and sets the style of the drawing.

The drawing interface includes: draw points, draw lines, draw pictures, draw polygons, draw words and so on. Drawing styles include color, lineweight, font size, gradient, and so on.

CPU to complete the 2D operation. Or use 3D graphics interface (OpenGL) to complete.

3D drawing context: supports CSS3D, WebGL, etc.

Use 3D graphics interface (OpenGL, Direct3D, etc.)

two。 Rendering mode

Software rendering: CPU. Usually the result of rendering is a bitmap, which is used when drawing each layer, except that the position may be different, and each layer is in the order from back to front. There is no need to assign a bitmap to each layer, there is no need to synthesize.

Disadvantages: new technologies for HTML5

Lack of capacity, CSS3D, WebGL

Poor performance, such as video, Canvas 2D

Usage is declining, especially on the mobile side.

Advantages: for update area processing, software rendering may only need to calculate very small areas, while hardware may need to draw one or more layers and then compose them. The hardware costs a lot.

Hardware accelerated rendering: GPU must have compositing steps. Layered rendering + compositing. However, for the update area, if it is only on one layer, the hardware may be faster.

How to implement WebKit:

Use appropriate page layering techniques to reduce recalculated layouts and drawings.

Use CSS 3D deformation and animation techniques. CSS 3D deformation technology allows browsers to animate all layers using only a compositor. No need for layout calculation and redrawing ~

Front-end optimization recommendations:

Reduce redrawing: because redrawing involves calculating layout, drawing, and compositing. Among them, the calculation of layout and drawing is more time-consuming, and the synthesis is less.

"how to understand the web rendering engine and front-end optimization" content is introduced here, thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report