In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces "how to understand and master the rearrangement and redrawing of web front-end performance optimization". In daily operation, I believe many people have doubts about how to understand and master the rearrangement and redrawing of web front-end performance optimization. the editor consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful for you to answer "how to understand and master the rearrangement and redrawing of web front-end performance optimization". Next, please follow the editor to study!
one。 Rearrange & redraw
Experienced bosses must be familiar with the concept of "what happened to browsers typing URL". It is estimated that everyone is already familiar with it, from the computer network to the JS engine, all the way to the browser rendering engine. The more experience you have, the deeper you can understand. Interested students can take a look at this article, the depth and breadth of the process from entering URL to page loading? How to improve your front-end knowledge system by one problem!
Let's get back to the point and let's continue to discuss what rearrangement is. After the browser has downloaded all the resources on the page, it starts to build the DOM tree, and at the same time it builds the render tree (Render Tree). (in fact, Style Tree is built at the same time as the DOM tree before building the render tree. DOM tree and Style Tree are merged into render tree)
DOM tree
Represents the structure of the page
Render Tr
Represents how the nodes of the page are displayed
Once the render tree is built, it's time to paint the page elements. When a change in DOM causes changes in the geometric attributes of an element, such as changing the width and height of the element and the position of the element, the browser has to recalculate the geometric properties of the element and rebuild the rendering tree, a process called "rearrangement". After the rearrangement is completed, the reconstructed render tree is rendered to the screen, which is called "redrawing". To put it simply, rearrangement is responsible for updating the geometric attributes of the element, and redrawing is responsible for updating the style of the element. Moreover, rearrangement will inevitably lead to repainting, but repainting may not necessarily lead to rearrangement. For example, changing the background of an element does not involve the geometric attributes of the element, so only redrawing occurs.
two。 Rearrangement trigger mechanism
As mentioned above, the fundamental principle of rearrangement is that the geometric attributes of the elements have changed, so we start from the point of view that we can change the geometric attributes of the elements.
Add or remove visible DOM elements
Element position change
The size of the element itself has changed.
Content change
Page renderer initialization
Browser window size changed
three。 How to optimize performance
The cost of redrawing and rearranging is very expensive, and if we keep changing the layout of the page, it will cause the browser to spend a lot of money on calculating the page, so that our page can be used by users. There will be obvious stutters. Today's browsers have actually optimized the rearrangement, such as the following code:
Var div = document.querySelector ('.div'); div.style.width = '200pxrabbit; div.style.background =' red'; div.style.height = '300px'
For older browsers, this code will trigger 2 page rearrangements, and trigger 2 times when setting width and height respectively, which is optimized by contemporary browsers, which is similar to the virtual DOM used by the popular MVVM framework, which collects dependencies on changed DOM nodes, confirms that there are no changed nodes, and then makes an update. However, although the idea of browser optimization for rearrangement is similar to that of virtual DOM, there is still an essential difference. Most browsers optimize the rearrangement process by queuing changes and executing them in batches. In other words, the above code actually constitutes only one rearrangement under the current browser optimization.
However, there are still some special geometric properties of elements that can cause this optimization to fail. For example:
OffsetTop, offsetLeft,...
ScrollTop, scrollLeft,...
ClientTop, clientLeft,...
GetComputedStyle () (currentStyle in IE)
Why does it cause optimization failure? If you take a closer look at these attributes, they are geometric or layout attributes that need to be fed back to the user in real time, and of course you can no longer rely on the optimization of the browser, so the browser has to immediately perform the "pending changes" in the rendering queue, and then trigger the rearrangement to return the correct value.
Next, we will introduce in depth several small TIPS with optimized performance.
3.1 minimize redrawing and rearrangement
Since rearranging & redrawing will affect the performance of the page, especially bad JS code will magnify the performance problems caused by rearrangement. Such being the case, the first thing that comes to mind is to reduce rearrangement and redrawing.
3.1.1. Change the style
Consider the following example:
/ / javascript var el = document.querySelector ('.el'); el.style.borderLeft = '1pxregions; el.style.borderRight =' 2pxtrees; el.style.padding = '5px'
This example is actually the same thing as the above example, which, in the worst case, triggers three browser rearrangements. However, a more efficient way for geese is to merge all the changes at once. This only modifies the DOM node once, for example, using the cssText attribute instead:
Var el = document.querySelector ('.el'); el.style.cssText = 'border-left: 1px; border-right: 2px; padding: 5px'
Along this line of thinking, the smart old man must have said that it is not appropriate for you to change the name of the class directly. Yes, another way to reduce rearrangement is to switch class names instead of using inline-style cssText methods. Using the toggle class name looks like this:
/ / css .active {padding: 5px; border-left: 1px; border-right: 2px;} / / javascript var el = document.querySelector ('.el'); el.className = 'active'
3.1.2 batch modification of DOM
If we need to make multiple changes to the DOM element, how can we reduce the number of rearrangements and redrawings? Some students are going to say again, don't you just use the above method to modify the style? Looking back at several key points resulting in page rearrangement, you can clearly see that a change in the geometric attributes of the element will trigger the rearrangement. Now you need to add 10 nodes, which inevitably involves modification of DOM. At this time, you need to use the optimization method of batch modification DOM. Here you can also see that the optimization method of changing style to minimize redrawing and rearrangement is applicable to a single existing node.
The core idea of batch modification of DOM elements is:
Detach the element from the document stream
Make multiple changes to it
Bring the element back to the document
For example, our host hard drive has a failure, the common way is to remove the hard drive, use professional tools to test where there is a problem, and then install it after repair. If you use a screwdriver directly on the motherboard, it is estimated that the motherboard will be broken for a while.
This process leads to two rearrangements, step 3 and step 3. Without these two steps, you can imagine that each addition or deletion of DOM in the second step will lead to a rearrangement. So once we know the core idea of batch modification of DOM, we learn about three ways to get elements out of the document stream. Note that floating & absolute positioning in css is not used here, which is an irrelevant concept.
Hide the element, modify it, and then show it
Use document fragments to create a subtree and then copy it to the document
Copy the original element to a separate node, manipulate the node, and then overwrite the original element
Take a look at the following code example:
/ / html xiaomi miui / / javascript now needs to add the li node let data = [{name: 'tom', url:' https://www.baidu.com',}, {name: 'ann', url:' https://www.techFE.com'}]
First, let's write a general method for updating new data to a specified node:
/ / javascript function appendNode ($node, data) {var a, li; for (let I = 0, max = data.length; I < max; iTunes +) {a = document.createElement ('a'); li = document.createElement ('li'); a.href = data [I] .url; a.appendChild (document.createTextNode (data [I] .name)); li.appendChild (a); $node.appendChild (li);}}
First of all, we ignore all the rearrangement factors, and people are bound to write this:
Let ul = document.querySelector ('# mylist'); appendNode (ul, data)
Using this method, each insertion of a new node results in a rearrangement without any optimization (we will discuss rearrangement first, because rearrangement is a * step of performance optimization). Consider this scenario, if we add a large number of nodes, and the layout is complex, the style is complex, then you can think of your page must be very stuttering. We use the optimization method of batch modification of DOM to reconstruct.
1) hide the element, modify it, and then display the element
Let ul = document.querySelector ('# mylist'); ul.style.display = 'none'; appendNode (ul, data); ul.style.display =' block'
This method results in two rearrangements, which are to control the display and hiding of elements. This approach can be considered for complex, large number of node paragraphs. Why do you use the display attribute, because when display is none, the element is not in the document stream? if you are not familiar with it, you can manually Google it, display:none, opacity: 0, visibility: hidden.
2) use the document fragment to create a subtree, and then copy it to the document
Let fragment = document.createDocumentFragment (); appendNode (fragment, data); ul.appendChild (fragment)
I prefer this method, the document fragment is a lightweight document object, it is designed for updating, moving nodes and other tasks, and the document fragment has another advantage is that when adding a document fragment to a node, add a child node group of the document fragment, itself will not be added. Unlike the * method, this method does not cause the element to disappear briefly and cause logical problems. In the above example, only one rearrangement is involved when adding a document fragment.
3) copy the original element to a separate node, manipulate the node, and then overwrite the original element
Let old = document.querySelector ('# mylist'); let clone = old.cloneNode (true); appendNode (clone, data); Old [XSS _ clean] .replaceChild (clone, old)
We can see that there is only one rearrangement in this method. In general, with document fragments, you can manipulate less DOM (compared to using cloned nodes) and minimize the number of rearrangements and redraws.
3.1.3 caching layout information
The concept of cache layout information has been mentioned many times in the performance optimization of "high-performance JavaScript" DOM. For example, if I want to get 100 li nodes under the ul node of the page, the way to * is to save it after *, reduce the access of DOM to improve performance, and cache layout information is the same concept. As mentioned earlier, when accessing properties such as offsetLeft,clientTop, it breaks through the browser's own optimizations-reducing the number of rearrangements / reprints by queuing modifications and batch runs. Therefore, we should try our best to reduce the number of queries for layout information, assign it to local variables and use local variables to participate in the calculation.
Look at the following example:
Translate the element div to the lower right, each time you move 1px, starting position 100px, 100px. Code with poor performance:
Div.style.left = 1 + div.offsetLeft + 'px'; div.style.top = 1 + div.offsetTop +' px'
The problem is that the offsetLeft of div is accessed every time, causing the browser to force the rendering queue to refresh to obtain the offsetLeft value of * *. A better way is to save this value and avoid duplicating it.
Current = div.offsetLeft; div.style.left = 1 + current + 'px'; div.style.top = 1 + current +' px';, the study on "how to understand and master the rearrangement and redrawing of web front-end performance optimization" is over. I hope to be able to solve everyone's doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.