Search code examples
javascripthtmlperformancedomreflow

Disable the browser's reflow\redraw


I'm adding quite a few elements to the DOM. I don't want the browser to attempt to redraw the page until all the elements are added.

Is this possible?


Solution

  • Just create a new element, add all your elements to that element and then finally add that element to the DOM so it only redraws once.

    One way to do this without adding an extra intermediate node to the html is to use a DocumentFragment

    const numbers = document.getElementById("numbers");
    const button = document.getElementById("button");
    
    button.addEventListener("click", function() {
      const temp_holder = new DocumentFragment();
      for(let i = 1; i < 6; i++) {
        const li = document.createElement("li");
        li.textContent = i.toString();
        temp_holder.appendChild(li);
      }
    
      numbers.appendChild(temp_holder);
    });
    <ul id="numbers">
      <li>0</li>
    </ul>
    <button id="button" type="button">Add numbers</button>