Quick Tip – Too Much DOM Manipulations Can Hurt You
DOM Manipulations and Reflows
The Customer’s Problem
In the customer scenario they needed to create a big DOM part according to some data they received from the server. The problem was that they made changes to the DOM for each element that they got. Since we are talking about adding and manipulating a lot of elements the performance of the app was really bad. The first thing I did was to open Chrome developer tools and to capture their app in the Timeline. What I saw was that a lot of app time was spent on rendering and painting. Then, I asked the developer to show me the code that create the DOM part and saw that he created the new DOM part using jQuery each function and appending the created elements straight into the DOM in each iteration. Here is a simple example of such operation without using jQuery each function:
In the example, five div elements are added to a given element. In each iteration a reflow process might be triggered due to changes in the DOM and cause a decrease in the performance.
A way to solve the previous problem is using a document fragment and appending it to the DOM. All the document fragment’s elements will be appended to the supplied element and we will have only one reflow. Here is the fixed code block:
As you can see, I’m using the document.createDocumentFragment function to create a DocumentFragment element. Then, I’m appending all the created divs to that element. After the loop’s end I’m appending the fragment to the element.
After fixing the problem we managed to decrease the performance of the app by ~50%. The app’s code is doing all the manipulations in memory and only in the end the change is appended to the DOM. Understanding what can cause performance problems can help you avoid those problems in the future.