In the 6.3.5: Creating and Manipulating nodes section of the JavaScript Advanced programming program, there are several ways to dynamically create HTML nodes, including the following common methods:
· Crateattribute (name): Create an attribute node with the name specified
· Createcomment (text): Create a comment node with text
· Createdocumentfragment (): Create a document fragmentation node
· CreateElement (tagname): Create a node with a label named TagName
· createTextNode (text): Creates a text node that contains textual text
One of the most interesting and previously untouched methods is the Createcomment (text) method, The book says: When you update a small number of nodes can be added directly to the Document.body node, but when you want to add a lot of data to the document is, if you add these new nodes directly, this process is very slow, because each add a node will call the parent node AppendChild () method, in order to solve this problem, you can create a document fragment, attach all the new nodes to it, and then add the document fragments to the documents at once.
If you want to create 10 paragraphs, you might write this code in a regular way:
123456 |
for
(
var
i = 0 ; i < 10; i ++) {
var
p = document.createElement(
"p"
);
var
oTxt = document.createTextNode(
"段落"
+ i);
p.appendChild(oTxt);
document.body.appendChild(p);
}
|
Of course, this code runs without a problem, but he calls 10 times document.body.appendChild () to produce a page render every time. Fragments are very useful at this time:
1 |
var oFragment = document.createDocumentFragment(); |
12345 |
for
(
var i = 0 ; i < 10; i ++) {
var
p = document.createElement(
"p"
);
var
oTxt = document.createTextNode(
"段落"
+ i);
p.appendChild(oTxt);
oFragment.appendChild(p);<br>}
|
1 |
document.body.appendChild(oFragment); |
In this code, each new <p/> element is added to the document fragment, and the fragment is passed as a parameter to AppendChild (). The call to AppendChild () does not actually append the fragment of the document to the BODY element, but only the child nodes in the fragment, and then you can see a noticeable performance increase, document.body.appenChild () replaced 10 times, This means that only one content rendering refresh is required.
Javascript-The Createdocumentfragment () method of document