When using JavaScript, DOM operations are the most common. With the development of Web Front-end technology, we are increasingly using JavaScript to operate DOM elements, for example, if you get data through an ajax request and then update the elements on the page, we usually use a node-like operation. appendChild. This method is unbuffered. That is to say, every time we call the appendChild method, the browser will re-render the page. Of course, there is nothing wrong with using this method, because we usually update a small number of DOM nodes without causing too many performance problems, however, if a large number of DOM nodes are updated, the performance gap will become more and more obvious. Because browsers need to constantly render pages, especially some complicated labels, a large number of re-rendering consumes a lot of performance and affects the user experience. So is there any good way to improve the efficiency of such DOM operations?
Although we usually encounter this situation in development, we still need to know about it. JS provides a DocumentFragment mechanism. I believe everyone is familiar with this, it provides a buffer mechanism to put DOM nodes in the memory first. After all nodes are constructed, add the DocumentFragment object to the page, at this time, all nodes will be rendered once, which can reduce the burden on the browser and significantly improve the page rendering speed. For example, the following code:
Copy codeThe Code is as follows:
Function CreateNodes (){
For (var I = 0; I <10000; I ++ ){
Var tmpNode = document. createElement ("div ");
TmpNode. innerHTML = "test" + I + "<br/> ";
Document. body. appendChild (tmpNode );
}
}
Function CreateFragments (){
Var fragment = document. createDocumentFragment ();
For (var I = 0; I <10000; I ++ ){
Var tmpNode = document. createElement ("div ");
TmpNode. innerHTML = "test" + I + "<br/> ";
Fragment. appendChild (tmpNode );
}
Document. body. appendChild (fragment );
}
The above Code provides two functions: Adding 10 thousand div nodes to the page using the common DOM method and DocumentFragement method. you can experiment with them by yourself, the second method is much faster than the first one. Here is just a simple tile addition of div labels. If it is a more complex HTML Tag or a multi-layer nested tag, the performance gap will become more obvious.
Through the above example, when developing JavaScript applications, if you encounter such a large number of nodes, you may wish to use DocumentFragment as an alternative.