Speed/efficiency of multiple DOM appendChild
Asked Answered
B

1

6

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);
}

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?

Thanks :)

Basin answered 7/3, 2012 at 9:37 Comment(2)
If you have to comment your code to explain what your function parameters are then you've named them badly.Rubbish
Point taken. I don't need to name them, really. The original code had the full names, and I just cut and pasted when I was tidying. BTW, I'm not sure you'll feel so fired up about it in 20 years :)Basin
S
11

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);

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.)

If you want to benchmark your specific use case using both approaches, create a jsPerf test case.

Staircase answered 7/3, 2012 at 9:38 Comment(6)
+1 from me before the .innerHTML police arrive ;-) I'd go with the document fragment approach, regardless.Incurious
You should add that the slowest in JS is DOM manipulation (not taking into account the re-rendering). This is why adding only one node will be faster than seven, even if they're smaller.Debarath
Thanks for all this, not least the jsPerf lead. I'd been wondering how I can benchmark stuff recently. I appreciate the help :)Basin
@MathiasBynens - I can't get a nested fragment working! I can create a fragment, append children and add it to the DOM. But how do I add children to the children within the fragment?Basin
For anyone in the future: the answer to the nesting question in my last comment is here: #9652920 :)Basin
For those who are interested, see the test case: jsperf.com/innerhtml-rdc2 The fragment wins hands down.Basin

© 2022 - 2024 — McMap. All rights reserved.