[英]In IE Javascript execution speed is slower than Firefox, Safari and Chrome
[英]Why is jQuery's .each drastically slower in Safari than Firefox/Chrome?
这个问题不是要寻找特定问题的解决方案,而是要了解为什么Safari在这种情况下效率低下。 当我谈论的速度大大降低时,代码在Firefox和Chrome中运行的时间不到1秒,而Safari则需要30-90秒的时间。 这可能已经是一个已记录的问题,但我不知道为什么。
情况是我有一个很大的HTML表。 它是1,000-1,500行,宽40列。 结构看起来像:
<table id="myTablePlayers" class="tablesorter table table-striped table-bordered table-hover" style="overflow: visible">
<thead>
<tr>
<th>...</th>
<th>...</th>
<th>...</th>
<th>...</th>
...
<th>...</th>
</tr>
</thead>
<tbody>
<tr class="playerData">
<td>...</td>
<td>...</td>
<td>...</td>
<td>...</td>
...
<td>...</td>
</tr>
...
</tbody>
</table>
许多表单字段允许用户选择和输入有助于过滤出行的信息。 jQuery看起来像:
function autoRank() {
// auto number
rank = 0;
$("#myTablePlayers .playerData").each(function() {
if ($(this).css("display") != "none") {
rank++;
$(this).find('td').eq(colRank).text(rank);
}
});
}
function filterTable() {
// Need some error checking on input not number
minGP = $("#mingp").val()
teams = $("#teamFilter").val()
position = $("#position").val()
age = $("#age").val()
$("#myTablePlayers .playerData").show();
$("#myTablePlayers .playerData").each(function() {
toHide = false;
if (teams != "") {
if ( !$(this).find('td').eq(colTeam).text().toUpperCase().includes(teams.toUpperCase())) {
toHide = true;
}
}
if ( Number($(this).find('td').eq(colGP).text()) < minGP ) {
toHide = true;
}
if (position != "") {
if (position == "D") {
if ($(this).find('td').eq(colPos).text().indexOf("D") == -1) {
toHide = true;
}
} else if (position == "F") {
if ($(this).find('td').eq(colPos).text().indexOf("D") != -1) {
toHide = true;
}
} else if ( $(this).find('td').eq(colPos).text() != position) {
toHide = true;
}
}
if (age != "") {
column = Number($(this).find('td').eq(colAge).text())
age = Number(age)
if ( column < age || column >= age+1 ) {
toHide = true;
}
}
if (toHide == true) {
$(this).hide();
}
});
autoRank();
}
$("#teamFilter").on('change', filterTable);
$("#mingp").on('change', filterTable);
$("#position").on('change', filterTable);
$("#age").on('change', filterTable);
当我开始删节代码时,不管循环中有什么内容,要花很长时间才能运行的有问题的代码似乎是$("#myTablePlayers .playerData").each(function() {...
我通过在Vanilla JS中重新编写代码来解决了该问题,但这无法回答为什么此代码在一个浏览器中效率如此低下的原因。
通过.css()
进行查询来检查DOM状态可能非常昂贵。 代替具有隐藏/揭示元件.hide()
和.show()
添加/删除的类。 在您的CSS中:
.hidden { display: none; }
然后,您的.each()
循环可以只检查该类:
$("#myTablePlayers .playerData").each(function() {
if (!$(this).hasClass("hidden")) {
rank++;
$(this).find('td').eq(colRank).text(rank);
}
});
要隐藏某些东西,您只需添加该类,并显示该类即可将其删除:
if (toHide) {
$(this).addClass("hidden");
}
并显示:
$("#myTablePlayers .playerData").removeClass("hidden");
现在,所有这些.find()
和.text()
调用也将变得昂贵。 可能值得通过以下方式来初始化表:检查一次表并在每个<tr>
上创建数据属性,以有效地缓存每一行中有趣的值。 通过jQuery的.data()
查找将比通过DOM中的选择器查找便宜得多(尽管现代DOM实现非常快)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.