简体   繁体   中英

Tips to improve performance of Javascript

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 ?

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.

dup_rows[i].style.height = rows[i].style.height更好吗?

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM