Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

Before we get into this method, we should first understand what the browser does when the node is inserted.

In general, when working with the DOM structure, it is often said that it is very performance costly because we add new elements to the DOM and the DOM updates immediately. If you add 100 nodes, you have to update 100 times, which is a waste of resources.

In the browser, as soon as we add a node to document.body (or any other node), the page will update to reflect the change, and for a few updates, the sequential insertion loop will work fine, which is the usual approach. The code is as follows:

for(var i=0; i<5; i++) { var op = document.createElement("span"); var oText = document.createTextNode(i); op.appendChild(oText); document.body.appendChild(op); }Copy the code

However, if we want to add a large amount of data to the document (say 1W), the process can be slow if we add nodes one by one as in the code above.

If we insert a lot of DOM elements into the page like the code above, the rendering process is very slow.

Every time a DOM node is inserted, the browser will trigger a rearrangement redraw. To improve efficiency, the rearrangement redraw should be minimized, that is, DOM node insertion should be reduced. One way to do this is with document fragments.

Document fragments is a kind of virtual DOM node, exists in memory, and there is no relationship between the actual DOM node, when we need to insert a node that many child node, then completely more child nodes can be inserted into the first document fragments, fragments after all child nodes in the document, then insert the document fragments to the actual node, This reduces the number of times nodes are inserted directly into the parent node, so instead of triggering rearrangement and redrawing multiple times, you only need to trigger rearrangement and redrawing once.

To solve this problem, we can use the document shard createDocumentFragmnet () method, which creates a document shard, puts the document to be created into the document shard, and then adds it to the page once, thus increasing the page speed somewhat.

The code is as follows:

/ / to create a document fragment var oFragmeng = document. CreateDocumentFragment (); for(var i=0; i<10000; i++) { var op = document.createElement("span"); var oText = document.createTextNode(i); op.appendChild(oText); Ofragmeng.appendchild (op); } / / finally disposable added to the document in the document. The body. The appendChild (oFragmeng);Copy the code

After testing, in IE, Firefox performance significantly improved. You can test it yourself. Front-end performance optimization starts with a few details, and if you don’t pay attention to them, the consequences can be serious.