- Are there any other optimization techniques or best practices I can apply to improve the performance of this script?
Code snippet:
// Simplified example
$('#table-body').empty();
data.forEach(function(row) {
$('#table-body').append('<tr>...</tr>');
});
- I’m using jQuery 3.6 to dynamically update a table with thousands of rows based on user input.
- The script uses
.append()
and.remove()
methods to update the table contents. - However, with large datasets, the script takes several seconds to execute, causing a noticeable delay.
- I’ve tried using
.detach()
and.empty()
instead, but the performance improvement is minimal.
2
Each append will modify the DOM, which is inefficient
Try this – I assume the data can be trusted and has been sanitized
$('#table-body').html(
data.map((row) => `<tr><td>${row.somevalue}</td></tr>`).join('')
);
In plain JS
document.getElementById('table-body').innerHTML = data
.map((row) => `<tr><td>${row.somevalue}</td></tr>`).join('');