In the use of JavaScript, Dom operation is the most common, with the development of Web front-end technology, we are more and more use JS to manipulate the DOM elements, such as through Ajax request to get the data, and then update the elements on the page, in general, This is done in a way that is similar to the Node.appendchild (). This method is not buffered, which means that every time we call the AppendChild method, the browser will render the page again. Of course, there is nothing wrong with this approach, as we typically update a small number of DOM nodes and do not cause too much performance problems, but the performance gap becomes more apparent if a large number of updates are made to the DOM nodes. Because browsers want to constantly render pages, especially some complex tags, a large number of rendering is very consuming performance, affecting the user experience. So what's a good way to improve the efficiency of this kind of dom operation?
Although we usually encounter this situation in the development of the time is not much, however, it is necessary to understand that JS provides a documentfragment mechanism, I believe you are not unfamiliar with this, it can provide a buffer mechanism, the DOM node first put in memory, when the node is constructed after the completion of the Then add the DocumentFragment object to the page, then all nodes will be rendered at once, this can reduce the burden of a lot of browsers, significantly improve the page rendering speed. For example, the following code:
Copy Code code 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 gives two functions, respectively, using the normal Dom method and documentfragement two ways to add 10,000 div nodes to the page, you can experiment with it, the second way is much faster than the first one. Here is just a simple div tag tile Add, if it is more complex HTML tags or multilayer nested tags, then the performance gap will be more obvious.
With the above example, when you develop JavaScript applications, if you encounter such a large number of nodes, you may wish to documentfragment as an alternative solution.