Reputation: 145
I have a requirement where I need to set the height of each row of a table based on the corresponding row in another table.The table has around 500 rows. I have written the below Javascript, but the performance is really bad around 8000 ms. How can I make this faster, appreciate any tips .
var start = new Date().getTime();
var rows = document.getElementById("table1").rows;
var dup_rows = document.getElementById("table2").rows;
var num_rows = rows.length;
var num_dup = dup_rows.length;
for (var i = 0; i < num_rows; ++i) {
var hg = rows[i].offsetHeight;
rows[i].style.height = hg +'px';
dup_rows[i].style.height = hg +'px';
}
var end = new Date().getTime();
var time = end - start;
alert('Execution time: ' + time);
Based on the Suggestion to edit the tables outside of DOM, I tried the below, but the outerHeight / offsetHeight returns 0 when the table is removed from DOM.
clone_small = $('#table2').clone();
clone_main_tab = $('#table1').clone();
$("#table2").remove();
$("#table1").remove();
$(clone_main_tab).find("tr").each(function(i) {
var hg = 0;
hg = $(this).offsetHeight; // If I hard code the height it works
// alert(hg);
$(this).height(hg);
clone_small.find("tr").eq(i).height(hg);
});
How can I set the height of these rows outside the DOM ?
Upvotes: 0
Views: 135
Reputation: 145
I was finally able to achieve some improvement in performance by using the below code
$clone_table1 = $('#table1').clone();
$clone_table2 = $('#table2').clone();
$('#table2').remove();
$trow2 = $('#table1').find('tr');
$trow = $clone_table1.find('tr');
$trow3 = $clone_table2.find('tr');
$trow.each(function(i) {
var hg = 0;
hg = $trow2.eq(i).outerHeight();
$(this).height(hg);
$trow3.eq(i).height(hg);
});
$parent2.append($clone_table2);
$('#table1').remove();
$parent1.append($clone_table1);
Upvotes: 0
Reputation: 4264
Isn't dup_rows[i].style.height = rows[i].style.height
better?
Upvotes: 1
Reputation: 324650
Remove the element that you are modifying from the DOM, then re-insert them when you are done modifying them. This prevents the browser having to reflow the document with every change, only doing it once when you're all finished.
Upvotes: 2