I’m using jQuery. I have website feature that does an ajax search and returns a JSON result. The ajax callback then populates the rows of a table with the results. Generally, there are 100 rows per search that get inserted. Each row has a fair amount of data.
The code looks something like this (very much abbreviated):
function search() {
$.post("/search.php", { params: search_params }, searchDone, "json");
}
function searchDone(json) {
var $table = $("#result_table");
var html = "";
for(i=0; i < json.results.length; i++) {
html += rowHtml(results[i]);
}
$table.append(html);
}
function rowHtml(result) { /* much simplified version */
var html = "<tr><td>";
html += result.field1;
html += "</td><td>";
html += result.field2;
html += "</td></tr>";
return html;
}
The performance is slow. The browser tends to lock up when the html is appended to the table.
Any advice on how to optimize this? Would it be better for me to create the dom nodes rather than try to get jQuery to render the HTML?
You can try to push to an array and then append using array.join.
Are you always appending to the table? If not you should wrap all the rows in a tbody and then replace the existing tbody node. This is faster as it is really only one append rather than x.
UPDATE
Perf tests here by Mr Padolsey