jquery/javascript how to calculate width faster

≡放荡痞女 提交于 2019-12-05 22:19:19
Daniel Szabo

You might consider writing plain vanilla javascript for this. Might shave some milliseconds off your time.

var cells = myTable.rows[0].children;

for ( var i = 0; i < cells.length; i++ ){
   cells[i].style.width = cells[i].offsetWidth + "px";
}

Because you're using offsetWidth, you're not going to be able to get away from reflow. However, estimating the cell widths based on how many characters are in the TH (assuming the text doesn't wrap and you're using a fixed, monotyped font) and creatively applying CSS can greatly reduce reflow latency.

// Appends CSS Classes to stylesheet in doc head
function appendStyle(styles) {
  var css = document.createElement('style');
  css.type = 'text/css';

  // Browser compatibility check
  if (css.styleSheet) css.styleSheet.cssText = styles;
  else css.appendChild(document.createTextNode(styles));

  document.getElementsByTagName("head")[0].appendChild(css);
}

var cells       = myTable.rows[0].children;
var cellWidth   = 0;
var letterWidth = 5; // let's assume each letter is 5px wide
var classname   = '';
var styles      = '';

for ( var i = 0; i < cells.length; i++ ){
   classname         = "Cell" + i;
   cell[i].className = classname;
   cellWidth         = (letterWidth * cells[i].innerHTML.length);
   styles           += "." + classname + "{width:" + cellWidth + "px}";
} 

window.onload = function() { appendStyle(styles) };

You could take this even further by using document fragments (great writeup on performance benefits by John Resig) by rendering the whole things outside of the DOM at runtime and swapping the fragment in after the DOM is loaded...but seriously, at this point you've really got to ask yourself if the juice is worth the squeeze.

You could add an onload callback to each column individually where you set up its width. This way, instead of in a loop it happens as they load. Just an idea, but it could work.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!