我有一个页面使用 jQuery 加载 XML 文件,然后将其内容输出到页面。
最近,我在输出中添加了排序功能,导致 iPod Touch 上的 Safari 挂起 1 分钟以上或 2 分钟以上(取决于我排序的字段数量),而在 iPad 上挂起不到 1 分钟。在 Firefox 4.0.1 上,几秒钟内就会返回相同的排序。
恐怕这只是iOS的一个限制,但在我删除排序之前,也许可以进行优化。
在过滤器之前,XML 中有 357 个项目。筛选后有 199 个项目经过排序。
var videoGames = $($.parseXML(videoGameXml)).find("game");
videoGames = videoGames.filter(function (a) {
return ($(this).attr('addOn') != "true" && $(this).find('own').text() == "yes");
});
videoGames.sort(function (a, b) {
var firstTitle = $(a).find('title').text().toLowerCase();
var secondTitle = $(b).find('title').text().toLowerCase();
var firstSystem = ($(a).find("console").text() + " " + $(a).find("version").text()).toLowerCase();
var secondSystem = ($(b).find("console").text() + " " + $(b).find("version").text()).toLowerCase();
if (firstSystem != secondSystem) {
if (firstSystem > secondSystem) {
return 1;
} else {
return -1;
}
} else {
if (firstTitle > secondTitle) {
return 1;
} else if (secondTitle < firstTitle) {
return -1;
}
}
return 0;
});
videoGames.each(function () {
// runs quickly, so removed
});
请注意,如果我删除系统检查作为初始“优化”,则 iPod Touch 上的时间会减少一半,但仍然会导致上面提到的 1 分钟以上的挂起。
那么,这是 iOS 设备的限制吗?或者我可以优化我的排序吗?
每次执行 $(a) 时,它都会执行一组非常复杂的操作,因此您最好对其进行缓存。另外,如果系统不同,则不需要标题。这个版本应该会加速一点:
videoGames.sort(function (a, b) {
var first = $(a);
var second = $(b);
var firstSystem = (first.find("console").text() + " " + first.find("version").text()).toLowerCase();
var secondSystem = (second.find("console").text() + " " + second.find("version").text()).toLowerCase();
if (firstSystem != secondSystem) {
if (firstSystem > secondSystem) {
return 1;
} else {
return -1;
}
} else {
var firstTitle = first.find('title').text().toLowerCase();
var secondTitle = second.find('title').text().toLowerCase();
if (firstTitle > secondTitle) {
return 1;
} else if (secondTitle < firstTitle) {
return -1;
}
}
return 0;
});
您还可以缓存对象中的值
然后,代替:
var firstSystem = (first.find("console").text() + " " + first.find("version").text()).toLowerCase();
Do:
var firstSystem = first.data('system');
if (!firstSystem) {
firstSystem = (first.find("console").text() + " " + first.find("version").text()).toLowerCase();
first.data('system') = firstSystem;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)