我有一个 jquery 函数,它将标记添加到表的第一行。 我尝试使用追加,但它不起作用,所以我得到了一个非常慢的解决方案,并且以某种方式给出了错误“此页面上的脚本导致 Internet Explorer 运行缓慢...”
功能如
jQuery.fn.fixGridView = function () {
"use strict";
// var start = +new Date(); // log start timestamp
if (jQuery(this).is('table') && this.find('thead').length === 0) {
var theadv = "<thead><tr>" + this.find('tbody tr:first').html(); +"</tr></thead>";
this.find('tbody tr:first').remove();
var htmlv = this.html();
this.html(theadv + htmlv);
}
//var end = +new Date(); // log end timestamp
// var diff = end - start;
// alert(diff);
return this;
};
有人可以帮助我让这段代码运行得更快吗?
编辑:我必须使用 IE..这是要求(ie8)。 Edit2:我创建了js fiddle :http://jsfiddle.net/4xLzL/
最佳答案
为了提高渲染性能,您必须了解 DOM 操作(包括回流和重绘)是昂贵的操作。您的代码当前使用 <thead>
重新创建整个表。添加了大部分<tbody>
内容保持不变。这种大规模的表“重绘”效率非常低。尤其是当 in IE 8, where rendering tables is extra slow,你必须尽可能少地修改 DOM。
我重构了您的逻辑,通过将元素保存到要重复使用的变量中来最大程度地减少查找元素所执行的查找次数。另外,删除了.html('...')
调用重新呈现表,但使用 .prepend()
函数添加 <thead>
进入<table>
作为第一个 child 。
jQuery.fn.fixGridView = function () {
"use strict";
var start = +new Date(); // log start timestamp
if (this.is('table') && this.children('thead').length === 0) {
var firstRow = this.children('tbody').children('tr:first');
var thead = "<thead><tr>" + firstRow.html() + "</tr></thead>";
firstRow.remove();
this.prepend(thead);
}
var end = +new Date(); // log end timestamp
var diff = end - start;
alert(diff);
return this;
};
$(document).ready(function () {
$('table[id*="gvCategories"]').fixGridView();
});
继续在 IE8 中测试一下:http://jsfiddle.net/amyamy86/4xLzL/7/
关于javascript - 在 IE 8 中渲染 <table> 时如何提高性能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23421062/