多个DOM appendChild的速度/效率 [英] Speed/efficiency of multiple DOM appendChild
问题描述
我必须在一次点击中创建七个div元素 - 容器A包含A1,A2,A3和amp; A4,然后A2a& A2b内的A2b。我正在使用多个调用这个小函数:
I have to create seven div elements in one hit - container A which contains A1, A2, A3 & A4, and then A2a & A2b within A2. I am using multiple calls to this little function:
function u1(t,i,c,p){ // type,id,class_name,parent_id
var tag=document.createElement(t); // Create node to be appended
tag.id=i;
tag.className=c;
document.getElementById(p).appendChild(tag);
}
我的问题:是否有更节省时间的方法来捆绑七个在一起,然后只是做一个DOM追加?或者innerHTML是一个不错的选择吗?
My question: Is there is a more time-efficient way to bundle the seven together, and then just do one DOM append? Or is innerHTML a good option?
谢谢:)
推荐答案
你可以使用 .innerHTML
。另一种方法是使用文档片段:
You could just use .innerHTML
. An alternative would be to use a document fragment:
var fragment = document.createDocumentFragment();
function u1(t, i, c){ // type,id,class_name
var tag = document.createElement(t); // Create node to be appended
tag.id = i;
tag.className = c;
fragment.appendChild(tag); // will use `fragment` from the outer scope
}
// call u1() seven times
// then insert all the elements into the DOM all at once
document.getElementById('foo').appendChild(fragment);
文档片段创建起来有点慢,但从长远来看可以节省性能。例如,在这种情况下,您将从7个DOM插入到一个DOM插入。 (涉及DOM的任何内容在JavaScript中都是慢。)
Document fragments are a bit slow to create, but can save performance in the long run. In this case, for example, you go from 7 DOM insertions to just one. (Anything involving the DOM is slow in JavaScript.)
如果要使用这两种方法对特定用例进行基准测试,创建一个jsPerf测试用例。
If you want to benchmark your specific use case using both approaches, create a jsPerf test case.
这篇关于多个DOM appendChild的速度/效率的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!