2

I write a test for continuous batch dom update in the code below:

    const container = document.querySelector('#container');
    const button = document.querySelector('button');


    function fulfill(text) {
      container.innerHTML = '';
      for (let i = 0; i < 10000 * 3; i++) {
        const label = document.createElement('div');
        label.innerHTML = text;
        container.appendChild(label);
      }
    }

    button.onclick = function () {
      fulfill("Hello");
      fulfill("World");
    }
  <button>Click</button>
  <div id="container"></div>

If the fulfill function execute sequentially twice, the page should show Hello first, and then show World. But it seems only show World eventually

So I guess the browser seems optmize continuous batch dom update natively? But I can't find any documents or references about it. Which keywords should use to google it?

Nickolay
  • 31,095
  • 13
  • 107
  • 185
hh54188
  • 14,887
  • 32
  • 113
  • 184
  • There is https://stackoverflow.com/questions/714942/how-to-stop-intense-javascript-loop-from-freezing-the-browser for preventing browser freeze. – user202729 Aug 22 '19 at 15:09
  • And https://stackoverflow.com/questions/37039667/executing-multiple-dom-updates-with-javascript-efficiently says that reflows are queued. – user202729 Aug 22 '19 at 15:14
  • 1
    Heavy synchronous code blocks the browser - repainting only occurs after the event loop is free. – CertainPerformance Aug 23 '19 at 08:05

1 Answers1

2

Yes, the browser only repaints when no other tasks (e.g. JS) are executing on the event loop.

The browser also attempts to delay costly re-calculation of layout/style until the repaint, but a script can force it by asking for updated information about position and computed style of elements after modifying the DOM, which can cause performance issues.

The relevant keywords for searching are:

The detailed specification of the event loop and the place of the rendering step in the processing model is here. (The full spec's intended audience are browser vendors, so it's quite hard to follow for the uninitiated; there's a web developer edition, but it omits the detailed description of the event loop).

Nickolay
  • 31,095
  • 13
  • 107
  • 185