When something is appended to the DOM in memory, does that cause a browser reflow? Or is it only when the pixels on the screen are told to change that the reflow happens? For example:
Case 1: Img elements appended to the DOM one at a time
var parentDiv = $('#imgHolder');
var imgArray = []; // Array of img paths populated in another function
$.each(imgArray, function()
{
parentDiv.append(createImgEle(this)); // createImgEle() // returns an <img> with the right src
}
Case 2: Img elements are put in a separate array and then appended to the DOM
var parentDiv = $('#imgHolder');
var imgArray = []; // Array of img paths populated in another function
var tempArray = []; // Holds the img elements until its fully populated
$.each(imgArray, function()
{
tempArray.push(createImgEle(this));
}
parentDiv.append(tempArray);
Case 3: Either case 1 or 2 but by default, parentDiv is set to display:none;
and made visible after the each loop is done.
Basically, what I want to know is, does the browser only start to reflow when the pixels of the screen are told to change?
Btw, the code is only for example purposes and not in production so don't slam me for any logic errors. Thank you for any advice.
Basically, what I want to know is, does the browser only start to reflow when the pixels of the screen are told to change?
No, the browser reflows when the DOM changes. After that, it will repaint (tell the pixels on the screen to change).
For the details, have a look at this dev.opera.com article and the question When does reflow happen in a DOM environment?.
In short: There is of course optimisation for subsequent DOM changes, for example if you insert an array of elements in a loop. I would not expect your cases 1 and 2 to differ noticeable.
Only if you are doing really heavy DOM changes, you might need case #3. This makes reflows, should they happen during the insert loop, stop when encountering the hidden elements so they are basically prevented. However, the two display changes before and after the loop can lead to flickering in some browsers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With