DEV Community

Discussion on: Javascript DOM Manipulation to improve performance

Collapse
 
_developit profile image
Jason Miller 🦊⚛ • Edited

A detached tree (or disconnected tree) is a DOM tree that hasn't been added to the document yet. Mutating DOM nodes that are not currently appended to a document is extremely cheap.
Example:

Slow Version
Items are appended to the list, which is already "connected" because it has been inserted into document.body:

let list = document.createElement('ul');
document.body.appendChild(list);
for (let i = 0; i < 1000; i++) {
  let item = document.createElement('li');
  item.textContent = `Item ${i}`;
  list.append(item);
}
Enter fullscreen mode Exit fullscreen mode

Fast Version
All we have to change here is to move the document.body.appendChild(list) to the end.
Because items are appended to the list before the list is appended to document.body, building up each item and inserting it into the list is very cheap. Rendering can only happen after the very last line of code executes.

let list = document.createElement('ul');
for (let i = 0; i < 1000; i++) {
  let item = document.createElement('li');
  item.textContent = `Item ${i}`;
  list.append(item);
}
document.body.appendChild(list);  // we just moved this to the end
Enter fullscreen mode Exit fullscreen mode