Instructor: 0:01 We have an app that causes reflow. It adds an item to DOM and then queries the height of the wrapper. In this case, the mutation of the DOM is the appendChild. The measurement is the query of the wrappers height.
0:28 Let's get back to our code and see how to fix that. We just need to move the DOM measurement bar before the DOM mutation part. We copy the height query before the appendChild, refresh the page and start recording again, add a few boxes and stop the recording.
0:49 We now see that we have eliminated the reflow. That solution might be good for some cases, but in our case, we need to hide after the mutation. As we saw, if we measure after we mutate, it creates the reflow. The solution is to measure asynchronously and this way, the measurement is postponed to the next frame.
1:11 This can be done using setTimeout. Inside the setTimeout, we add the query, we refresh the page and start recording. Add a few boxes and stop the recording. Focus again and we see in the results that we have no reflow. Our measurement code is running after the layout calculation finished.
1:38 A better way to do that would be to use requestAnimationFrame. We just replace the setTimeout with requestAnimationFrame. In this case, it will have the same effect, but in bigger application, it will be more accurate. Let's refresh and record again. We look at the results and see there we'll still have no reflows.
2:00 In summary, reflow happens when we measure the DOM after we mutate it, and hence, we force the browser to recalculate the layout. We can solve this by either removing measurement before the mutation or by postponing the measurement to the next frame by setTimeout or requestAnimationFrame.