Avoid Layout Trashing using fastdom

Usually, updating DOM properties make the browser calculating the layout changes only after the frame so we can retrieve properties from the previous one.

However, one can easily trick the browser into a read-write-read-write cycle which forces the layout to be calculated multiple times in a single frame:

for (var i = 0; i < paragraphs.length; i++) {
    paragraphs[i].style.width = box.offsetWidth + 'px';
}

As it easily takes more than 16ms, Chrome even shows a warning message on the console:

[Violation] Forced Reflow while executing JavaScript took xx ms

This situation is called Layout Trashing and should be eliminated by batching rading and writing phases at the beginning and at the end of the frame, respectively. Fastdom comes to the rescue, using its measure and mutate function help us achive that really easily.

fastdom.measure(() => {
  // Read DOM properties
});

fastdom.mutate(() => {
  // Write DOM properties
});
Written by
Barnabás Bartha
Barnabas Bartha