title: How can I group Javascript actions that force reflow?
body: <p>I have a project which is responsible for managing the rendering of elements, but I'm running into a performance issue replacing elements and then focusing on whatever had focus before.</p>
  <p>Below is a minimal example that replicates the performance issue:</p>
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>const renderPage = () =&gt; {
    // get the old section element
    const oldSection = document.querySelector('section')
  
    // create a new section element (we'll replaceWith later)
    const newSection = document.createElement('section')
    
    // create the render button
    const newButton = document.createElement('button')
    newButton.innerHTML = 'Render Page'
    newButton.onclick = renderPage
    newSection.appendChild(newButton)
    
    // create a bunch of elements
    const dummyDivs = [...new Array(100000)].forEach(() =&gt; {
      const dummy = document.createElement('div')
      dummy.innerHTML = 'dummy'
      newSection.appendChild(dummy)
    })
    
    // replace the old page with the new one (causes forced reflow)
    oldSection.replaceWith(newSection)
    // reattach focus on the button (causes forced reflow)
    newButton.focus()
  }
  
  window.renderPage = renderPage</code></pre>
  <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;section&gt;
    &lt;button onclick="renderPage()"&gt;Render&lt;/button&gt;
  &lt;/section&gt;</code></pre>
  </div>
  </div>
  </p>
  <p>When running this locally, I see the following in the performance report in Chrome/Edge
  <a href="https://i.stack.imgur.com/z3R1C.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/z3R1C.png" alt="Performance Report, forced reflow is highlighted under both a replaceWith and focus event" /></a></p>
  <p>Both <code>replaceWith</code> and <code>focus</code> are triggering forced reflow. Is there a way to batch or group these actions so that only a single reflow occurs? I realize that there's no way to really get around this happening at all, but if I can batch them, I think that might improve my performance.</p>