1

It's not clear for me whether browser initiates reflow during script run time, or after execution. So basically, If I have a loop (100 iteration), that inserts an element into the DOM, the browser stops the script execution, recalculates the layout with the inserted element, repaints in every step? And then the next step comes? Or it inserts the 100 element without stopping, and then reflow comes?

To translate it to code, are there any performance difference beetween the two code?

for(let i = 0; i < 100; i++){
   $('body').append('<div>SOmething....</div>')
}

OR is it better?

let a = $('<div></div>');
for(let i = 0; i < 100; i++){
   $(a).append('<div>SOmething....</div>')
}
$('body').append(a)

Or maybe is there even a better and more efficient solution for inserting a huge amount of elements (10000 or even more) into the DOM the doesn't slow down the browser that much?

B. Ma
  • 221
  • 2
  • 15
  • Not sure about appending thousands of elements but, the browser has an (event)loop where it queues all its tasks. Whenever there is an update to the DOM it will fire repaint layout etc. Better and detailed explanation by Jake Archibald can be found [on YouTube](https://www.youtube.com/watch?v=cCOL7MC4Pl0) – Reyno Sep 23 '21 at 09:01

1 Answers1

0

In modern browsers the reflow will happen only when needed, that is, either in idle time (Safari), right before the next paint (in Chrome and Firefox, or Safari if no idle before), or when calling one of the few methods that do force a reflow (more details in this answer of mine).

Every modification to the DOM will not force a reflow on their own, in your code only one will happen, before the next repaint.

However, appending to the DOM itself does come with some cost, so yes, there is a performance difference between both codes, but this difference will be minimal.

Appending to a DocumentFragment may be better, in some cases building a huge markup string does work faster, but you really should reconsider your need for appending 10000 elements.
Instead, have you considered a pagination system, or an infinite scrolling one? This way you'd append only a small part of the whole every time, letting the browser breath and handle memory pressure. At the very least, you could consider appending your elements by batches, and let the event loop actually loop (and the browser render what it can) between each batch using setTimeout.

Kaiido
  • 123,334
  • 13
  • 219
  • 285