When we develop Rich Internet Applications (RIA), we often write some javascript scripts to modify or add page elements. These tasks are ultimately completed by DOM - or Document Object Model - and our implementation method will affect The response speed of the application.
DOM operations will cause the browser to re-parse (reflow), which is a calculation process of the browser that determines how page elements are displayed. Directly modifying the DOM, modifying the CSS style of an element, or modifying the browser window size will trigger reparsing. Reading an element's layout properties such as offsetHeithe or offsetWidth will also trigger reparsing. Reparsing takes computation time, so the less reparsing is triggered, the faster the application will be.
DOM operations usually either modify existing page elements or create new page elements. The following four optimization solutions cover two methods of modifying and creating DOM nodes, helping you reduce the number of times that triggers browser re-parsing.
Solution 1: Modify the DOM by switching CSS class names
This solution allows us to modify multiple style attributes of an element and its child elements at once and trigger only one reparse.
need:
( emu note : The author of the original article obviously had a short-circuit in his brain when he wrote this, and put the problems to be solved in the subsequent Out-of-the-flow DOM Manipulation mode here. However, it is easy to understand the author from the demonstration code. The problem I really want to describe, so emu will not reproduce the original text)
We now need to write a function to modify several style rules of a hyperlink. It is very simple to implement, just change the attributes corresponding to these rules one by one. But the problem is that every time a style attribute is modified, it will cause a re-parsing of the page.
function selectAnchor(element) {
element.style.fontWeight = 'bold';
element.style.textDecoration = 'none';
element.style.color = '#000';
}
Solution:
To solve this problem, we can first create a style name and put all the style rules to be modified on this class name. Then we add this new class name to the hyperlink, so that we can add several style rules and only A reparse is triggered. Another advantage of this model is that it also achieves the separation of performance and logic.
.selectedAnchor {
font-weight: bold;
text-decoration: none;
color: #000;
}
function selectAnchor(element) {
element.className = 'selectedAnchor';
}