jQuery data append tricks
thead section and empty
Starter html code
Now, we will include a minified jQuery source that we can find at Google developers. We will run the script with making sure that the tbody element is empty since this is where we will append our data, and open the on-click functionality that will roll out when we click the button that we have defined in our html.
jQuery append – opening statements
jQuery – opening function
Now we use this function to return the data and append it to a tbody – table element in a simple for loop and using the append() jQuery function. Prior to this we have defined a timer (using the Date object) at the beginning of the script, and at the end of the script, to measure the time necessary to perform the append execution loop.
jQuery – optimized append data example 1
JQuery provides several techniques to manipulate the DOM. Often we can ask ourselves a question, which one to use and which one is better. Depending on the amount of data and application structure, this can differ, but there are general rules of conduct which can apply almost always. Let us look at our example code. This code finds a table, and appends a bunch of data to this table tbody element. When the button on top of the page is clicked, jQuery appends to each table row, the hardcoded data extracted from getEmps() function, in form of a table cell for each piece of information. We check the time it took for this operation with our two time measuring functions. We can see how long it took to append all 6000 rows here (for me, almost 16 seconds), and yes, this is bad. The browser is almost non-responsive because of the slow time execution. Now, how do we clean this mess up, and make this work properly? First thing that we can do, is eliminate the “touching the DOM” that we do so many times with the append() function. Instead of this bad practice within the loop, what we should do is set one empty string variable (we can use an array also) and append the data ONCE, to this variable, and return it to the browser. This way, we touch the DOM only one time with the append function call. This makes a major, major difference and we can see this in seconds that we saved (I get less than 8 seconds execution time now), the positive execution result is obvious.
jQuery – optimized append data example 2
Second thing we can do here to further optimize our performance, is to use concatenation of data to an empty string variable, and perform the append function once, OUTSIDE of the loop itself. This makes even more difference in terms of execution time. Before that, what we also did, is caching the main DOM selector which can also add up to a better performance of this script.
jQuery – optimized append data example 3
Posted on: April 20, 2020
Print article Email article