Writing high performance jQuery code is a task that requires some basic knowledge of how jQuery's methods work internally. For example, the html()
method uses the clean()
method to preprocess the HTML string passed in as argument. This makes html()
much slower than the traditional innerHTML
property. When it comes to tables, tests have shown significant improvements in slower browsers when HTML tables are built as arrays of strings which are turned into a plain HTML string using the join()
method. Let's see how.
We want to create an HTML table containing 1,000 rows of data. Here's how we can do:
$(function() { var i = 0, html = []; html[i++] = '<table>'; html[i++] = '<tr><th scope="col">A</th><th scope="col">B</th>' + '<th scope="col">C</th><th scope="col">D</th></tr>'; for(var j = 1; j < 1001; j += 1) { html[i++] = '<tr><td>' + j + '</td>' + '<td>' + j + '</td>' + '<td>' + j + '</td>' + '<td>' + j + '</td></tr>'; } html[i++] = '</table>'; $('#test')[0].innerHTML = html.join(''); });
The dynamic array has been built by incrementing its index and adding a new HTML string each time. Finally, we use innerHTML
(not html()
) to display the resulting table by concatenating the array into a string via join()
. You can see the demo below.