This article analyzes the operation method of JavaScript document fragmentation through examples. Share it with everyone for your reference, the details are as follows:
Using document fragmentation can improve page efficiency in some cases.
Javascript operating DOM is a very performance-intensive process. In some cases, DOM loop operation has to be performed. Every operation we perform on DOM will trigger "rearrangement", which seriously affects energy consumption. Generally, The approach taken is to reduce DOM operations as much as possible to reduce "rearrangement".
Faced with the process of cyclic operation of dom, we choose to use document fragments (creatDocumentFragment), add the content that needs to be added to the dom to the document fragments at once, and then add the document fragments to the dom tree, so that it can be effective Reduce the number of DOM operations.
<!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>文档碎片</title> <meta name="Keywords" content=""> <meta name="author" content="@my_programmer"> </head> <body> <script> var temp = document.createDocumentFragment();//文档碎片(当把文档碎片付给某节点时,只是把文档碎片中的子节点付给了某节点,它本身并没有插入到这个节点中) for (var i=0; i<100; i++) { var test =document.createElement('div');//创建一个节点 test.innerHTML = 'aaa' + i;//给节点添加内容 temp.appendChild(test);//把创建的节点插入到temp文档中 } document.body.appendChild(temp);//把temp文档插入到body末尾 </script> </body> </html>
I hope this article will be helpful to everyone in JavaScript programming.