.height(item.height())在IE中jquery太慢了! 备择方案?
我试图设置绝对定位项的高度以匹配其容器元素的高度。 问题是这些元素有数百个。 标题中的标准代码在chrome中运行得很好,但在IE中拖得很疯狂。 我该如何缓解这个问题?
//Too SLOW in IE var starttime = new Date().getTime(); $("#grdSchedule > tbody > tr").each(function(i) { thisRow = $(this); thisRow.children(".stickyCol").height(thisRow.height()); //thisRow.children().slice(0, 1).css('height', thisRow.css('height')); }); var taskTime = (new Date().getTime() - starttime) / 1000; alert("cell height stretch: " + taskTime);
似乎只是设置高度并不会使它变得那么多,但是从其他东西的.height()设置高度确实会导致IE窒息。
我试过.css()而不是一点点提升但不是很多。
这是一个小提琴: 小提琴!
使用IE9,我从1.6秒变为0.031秒。 使用Chrome,我从0.302秒变为0.018秒。
使用detach()的工作示例 (最快,但如果延迟重新插入表,则会导致布局问题 – 也就是说,如果允许页面在没有DOM中的表的情况下重新渲染)。
使用普通DocumentFragment克隆的工作示例
关键是将表克隆为DocumentFragment(或者使用detach()
暂时将其从DOM中删除,并操纵克隆表的单元格高度(即,在表是DOM的一部分之前)。然后在所有高度计算之后已经完成,用克隆表替换原始表。
.height()
计算并没有减慢你的速度,这是你在一个大循环中遍历和操作DOM的事实。 在三大浏览器中,Internet Explorer是DOM操作中最慢的。
对于一些进一步的阅读,不久前我将一些DOM插入基准测试放在一起,可以很好地衡量DOM的相对浏览器性能。 John Resig还撰写了关于使用DocumentFragments和DOM操作的文章: http : //ejohn.org/blog/dom-documentfragments/
避免为行创建单独的对象,并缓存行的高度:
$('#grdSchedule > tbody > tr').each(function () { var height = $.css(this, height); $('.stickyCol', this).css('height', height ); });
设置height:100%
有什么问题height:100%
在绝对定位的元素上height:100%
?
更新小提琴
看起来像他们自己的预处理器足以真正加快速度,并且带来的好处是不用担心任何拆卸的复杂性
var starttime = new Date().getTime(); var stickyCols = 1; //get row heights var rowHeights = new Array(); $("#grdSchedule > tbody > tr").each(function(i) { rowHeights[i] = $(this).css('height'); }); //Now SUPERDUPERFAST in IE //var $table = $("#grdSchedule").detach(); $("#grdSchedule > tbody > tr").each(function(i) { //$(" > tbody > tr", $table).each(function(i) { thisRow = $(this); thisRow.children("td").slice(0, stickyCols).css('height', rowHeights[i]); }); //$("#scrollDiv_top").append($table); var taskTime = (new Date().getTime() - starttime) / 1000; alert("cell height stretch: " + taskTime);
小提琴