简体   繁体   English

改善Javascript性能的提示

[英]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. 我有一个需要根据另一个表中的相应行设置表的每一行的高度的要求,该表大约有500行。 I have written the below Javascript, but the performance is really bad around 8000 ms. 我已经写了下面的Javascript,但是性能在8000毫秒左右确实很差。 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. 根据建议在DOM外部编辑表,我尝试了以下操作,但是当从DOM中删除表时,outerHeight / offsetHeight返回0。

      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 ? 如何设置DOM外部这些行的高度?

Remove the element that you are modifying from the DOM, then re-insert them when you are done modifying them. 从DOM中删除要修改的元素,然后在完成修改后将它们重新插入。 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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