SoFunction
Updated on 2025-03-01

JavaScript Tips Speed ​​up DOM rendering with DocumentFragment

When you use JavaScript, DOM operations are the most common. With the development of web front-end technology, we are increasingly using JS to operate DOM elements, such as obtaining data through ajax request and then updating elements on the page. Generally speaking, we will complete this operation in a similar way to (). This method is unbuffered, which means that 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 in general, we update a small number of DOM nodes, which will not cause too much performance problems. However, if we update a large number of DOM nodes, the performance gap will become more and more obvious. Because the browser constantly renders the page, especially some complex tags, large-scale re-rendering consumes performance and affects the user experience. So is there any good way to improve the efficiency of this type of DOM operation?

Although we don't encounter many such situations in development, it is still necessary to understand that JS provides a DocumentFragment mechanism. I believe everyone is familiar with this. It can provide a buffering mechanism to put the DOM nodes into memory first. After the nodes are constructed, the DocumentFragment object is added to the page. At this time, all nodes will be rendered at once, which can reduce a lot of burden on the browser and significantly improve the page rendering speed. For example, the following code:

Copy the codeThe code is as follows:

function CreateNodes(){
for(var i = 0;i < 10000;i++){
var tmpNode = ("div");
= "test" + i + " <br />";
(tmpNode);
}
}
function CreateFragments(){
var fragment = ();
for(var i = 0;i < 10000;i++){
var tmpNode = ("div");
= "test" + i + "<br />";
(tmpNode);
}
(fragment);
}


The above code gives two functions, which are to add 10,000 div nodes to the page using the ordinary DOM method and DocumentFragment. You can experiment on your own. The second method is much faster than the first one. Here is just a simple tile addition of div tags. If it is more complex HTML tags or multi-layer nested tags, the performance gap will be more obvious.
Through the above example, when you are developing JavaScript applications, if you encounter such a large number of nodes, you might as well use DocumentFragment as an alternative solution.