JavaScript · Middle · Question 44 of 75
How do you efficiently insert 1000 elements into the DOM?
- ✓Correct answer: Collect them in a
DocumentFragment(or one array) and insert in a single operation - 2Insert them one by one with
appendChild- the browser will batch them itself - 3Rebuild the whole list via
innerHTML +=in a loop each time
Explanation
Each insertion into the live DOM can trigger style and layout recalculation. A fragment is built outside the document and inserted at once; el.append(...nodes) works the same way. innerHTML += in a loop reparses all the markup each time and loses handlers.