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 optimize page redrawing and reflow in web development

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

Share

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

Editor to share with you how to optimize page redrawing and reflow in web development, I believe most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's go to know it!

Before discussing page redrawing and reflow. You need to know something about the rendering process of the page, and how the page displays html with css to the browser. The following flowchart shows how the browser handles the rendering of the page. Different browsers may be slightly different. But it's basically similar.

The browser parses the acquired HTML code into a DOM tree, each tag in the HTML is a node in the DOM tree, and the root node is our commonly used document object. The DOM tree contains all the HTML tags, including display:none hiding, elements dynamically added by JS, and so on.

The browser parses all styles (user-defined CSS and user agent) into style structures, and removes styles that the browser does not recognize in the process of parsing. For example, IE removes the style starting with-moz, while FF removes the style starting with _.

3. DOM Tree and style structure are combined to build render tree. Render tree is similar to DOM tree, but it is very different. Render tree can recognize styles. Each NODE in render tree has its own style, and render tree does not contain hidden nodes (such as display:none nodes and head nodes), because these nodes will not be used for rendering and will not affect rendering, so they will not be included in render tree. Note that the hidden elements of visibility:hidden will still be included in render tree, because visibility:hidden will affect the layout and take up space. According to CSS2 standards, each node in render tree is called a Box (Box dimensions), understanding that a page element is a box with padding, margins, borders, and positions.

Once the render tree is built, the browser can draw the page based on the render tree.

Reflow and redrawing

When some (or all) of the render tree needs to be rebuilt due to changes in element size, layout, hiding, and so on. This is called reflow. Each page needs to be reflowed at least once, when the page is first loaded. When reflux, the browser invalidates the affected part of the render tree and reconstructs the part of the render tree. When the reflow is complete, the browser will redraw the affected part to the screen, which is called redrawing.

When some elements in render tree need to update attributes, and these attributes only affect the appearance and style of the element, but not the layout, such as background-color. It's called redrawing.

Note: reflow is bound to cause redrawing, and redrawing does not necessarily cause reflow.

When does backflow occur:

It needs to be backflowed when the page layout and geometric properties change. Browser backflow occurs in the following situations:

1. Add or remove visible DOM elements

2. Element position change

3. Element size changes-margins, fills, borders, width and height

4. Content changes-such as changes in calculated width and height caused by text changes or picture size changes

5. Page rendering initialization

6. Browser window size change-when the resize event occurs

Let's take a look at how the following code affects reflow and redrawing:

Var s = document.body.style;s.padding = "2px"; / / reflow + redraw s.border = "1px solid red"; / / reflow + redraw s.color = "blue"; / / redraw s.backgroundColor = "# ccc" again; / / redraw s.fontSize = "14px" again / / reflow + redraw / / add node, reflow + redraw document.body.appendChild (document.createTextNode ('abccalendar'))

At this point, we all know that the cost of reflux specific gravity painting is higher, and the cost of reflux has something to do with how many nodes of the render tree need to be rebuilt. Suppose you directly operate the body, for example, inserting an element in front of the body will cause the entire render tree to return. The cost will of course be higher, but if you refer to the insertion of an element after the body, it will not affect the reflux of the previous element.

Smart browser

From the previous example code, you can see that a few simple lines of JS code caused about 6 times of reflow and redrawing. And we also know that reflow costs a lot, and browsers may not be able to stand it if every JS operation is redrawn. Therefore, many browsers will optimize these operations. Browsers will maintain a queue and put all operations that will cause reflow and redrawing into this queue. When the number of operations in the queue reaches a certain number or at a certain time interval, the browser will flush the queue for batch processing. In this way, many times of repainting and redrawing will be turned into a redrawing.

Although there are browser optimizations, sometimes some code we write may force browsers to advance flush queues, so browser optimizations may not work. When you request some style information from the browser, you will ask the browser to queue flush, such as:

OffsetTop, offsetLeft, offsetWidth, offsetHeightscrollTop/Left/Width/HeightclientTop/Left/Width/Heightwidth,height requested getComputedStyle (), or currentStyle of IE

When you request some of the above properties, the browser needs the flush queue to give you the most accurate values, because there may be operations in the queue that affect these values. Even if you get the layout and style information of the element has nothing to do with the layout information that has occurred or changed recently, the browser will forcibly refresh the rendering queue.

How to reduce backflow and redraw

To reduce reflow and redraw is to reduce the operation of render tree (merging multiple DOM and style changes), and reduce the request for some style information, so as to make the best use of the browser's optimization strategy. The specific methods are:

Change the className directly, and if you change the style dynamically, use cssText (consider non-optimized browsers)

/ / the bad way to write var left = 1 el.style.cssText var top = 1 * eel.style.left = left + "px"; el.style.top = top + "px"; / / the better way to write el.className + = "className1"; / / the better way to write el.style.cssText + = "; left:" + left + "px; top:" + top + "px;"

Let the elements to be operated be "processed offline", and update together after processing.

A) use DocumentFragment for caching operation, causing a reflow and redrawing

B) using display:none technology to cause only two reflows and redraws

C) trigger a reflow and redraw using cloneNode (true or false) and replaceChild technology

3. Do not often access the properties that cause the browser flush queue. If you do, use the cache

/ / Don't write that, Big Brother for (Loop) {el.style.left = el.offsetLeft + 5 + "px"; el.style.top = el.offsetTop + 5 + "px";} / / write var left = el.offsetLeft,top = el.offsetTop,s = el.style; for (Loop) {left + = 10; top + = 10; s.left = left + "px"; s.top = top + "px";}

Let the elements break away from the animation stream and reduce the size of the reflux Render Tree

$("# block1"). Animate ({left:50}); $("# block2") .animate ({marginLeft:50})

Case test

Finally, two tools are used to test the above theory, namely: dynaTrace (test ie) and Speed Tracer (test Chrome).

The first test code does not change the rules, size, and location of the element. Only change the color, so there is no reflow, just test the redraw, the code is as follows:

Var s = document.body.style; var computed; if (document.body.currentStyle) {computed = document.body.currentStyle;} else {computed = document.defaultView.getComputedStyle (document.body,'');} function testOneByOne () {s.color = 'red';; tmp = computed.backgroundColor; s.color =' white'; tmp = computed.backgroundImage S.color = 'green'; tmp = computed.backgroundAttachment;} function testAll () {s.color =' yellow'; s.color = 'pink'; s.color =' blue'; tmp = computed.backgroundColor; tmp = computed.backgroundImage; tmp = computed.backgroundAttachment;} color test Test All

The testOneByOne function changes the color three times, in which getComputedStyle is called after each change to read the attribute value (as we discussed above, this will cause the queue's flush). TestAll also changes the color three times, but getComputedStyle is not called immediately after each change.

We first click the Test One by One button, then click Test All, and use dynaTrace to monitor as follows:

As can be seen in the figure above, we have executed two click events of button, and the time after each click is about the same as that of one rendering,2 click function execution, 0.25ms, 0.26ms, but then the rendering time is more than doubled. In fact, most of the time, the performance bottleneck of the front end is not the execution of JS, but the rendering of pages, which is more prominent in rich clients. Let's look at the bottom part of the figure. This is the details of the rendering for the first time. We can see that there are two lines of Scheduleing layout task in it. This is the browser-optimized queue we discussed earlier, and you can see that we raised the flush twice.

If you look at the details of the second rendering, you can see that there is no Scheduleing layout task, so the time of this rendering is also relatively short.

Test code 2: this test is similar to the code that was tested for the first time, but with changes to layout in order to test backflow.

Var s = document.body.style; var computed; if (document.body.currentStyle) {computed = document.body.currentStyle;} else {computed = document.defaultView.getComputedStyle (document.body,'');} function testOneByOne () {s.color = 'red'; s.padding =' 1pxrabbit; tmp = computed.backgroundColor; s.color = 'white' S.padding = '2pxflux; tmp = computed.backgroundImage; s.color =' green'; s.padding = '3pxrabbit; tmp = computed.backgroundAttachment;} function testAll () {s.color =' yellow'; s.padding = '4pxrabbit; s.color =' pink'; s.padding = '5pxrabbit; s.color =' blue'; s.padding = '6px' Tmp = computed.backgroundColor; tmp = computed.backgroundImage; tmp = computed.backgroundAttachment;} color test Test All

As can be seen in this picture, with reflow, the time of rendering is three times higher than that of only redrawing before, which shows the high cost of reflux.

When you see it, pay attention to the details. There is more Calcalating flow layout than before.

Finally, use Speed Tracer to test, in fact, the result is the same, just to let you know the next two testing tools:

Test 1:

On the figure, the first click executes 2ms (50% of which is for style Recalculation), the second 1ms, and the first click is followed by 2 style Recalculation, while the second click has no style Recalculation.

But this test found that the time of paint redrawing is the same, all 3ms, which may be why chrome is better than IE.

Test 2:

From the figure, it is found that the second test result is exactly the same as the first one in time, which may be because the operation is too little and the chrome is more powerful, so the test results are not obvious.

But note that there is an extra purple part in the diagram, which is the part of layout. That's what we call backflow.

These are all the contents of the article "how to optimize page redrawing and reflow in web development". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

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