[英]Optimize javascript/jQuery for better performance
我制作了Chrome扩展程序,用于删除特定UL中的li元素。
例如我有
<ul>
<li id="1"><div class="l1"><p>test1</p></div></li>
<li id="2"><div class="l1"><p>test2</p></div></li>
<li id="3"><div class="l1"><p>test3</p></div></li>
.... and so on
</ul>
我有3500个项目(如数据库)的数组,在每个页面上重新加载都会检查此ul是否存在匹配项并将其删除。
我的jQuery代码是这样的:
var remove = function remove(items){
$.each(items, function(index,value){
if( $("div.l1 p").filter(function() { return $(this).text() == value; }).length ) // if there is match {
$("div.l1 p").filter(function(){ return $(this).text() == value; }).parent().parent().remove(); // delete li element
}
}
}
我这样称呼它:
var initi = function initi() // called when page is loaded
{
remove(Array("test1","test2","test3",...,"testonemilion"));
}
我发生的问题是chrome有时会随机耗尽内存,并需要重新加载页面。 我认为当“数据库”变大时,这种情况会更经常发生。
所以我想问问是否有可能的方法来优化我的jQuery函数,以降低内存压力?
我使用最新的Chrome 40.0.2214.115 m,计算机上有8GB RAM(永远不会达到100%)
谢谢!
编辑:也有调试工具将显示如何执行不同版本的功能(例如function1()执行1秒钟,function2()执行0.8秒,依此类推)
您可以使用filter()
来查看文本是否在数组中,因此只遍历元素一次,而不是像您那样做多次
var remove = function remove(items){
$("div.l1 p").filter(function(){
return $.inArray( $(this).text(), items) !==-1;
}).parent().parent().remove();
}
您的代码可以提高效率。 由于filter()
将返回具有匹配元素的对象,因此不需要if
语句。
您还应该将jQuery对象保留在一个变量中,以免必须为.each()
方法的每次迭代选择所有段落。
var remove = function remove(items){
var $p = $("div.l1 p");
$.each(items, function(index,value){
$p.filter(function(){
return $(this).text() == value;
}).parent().parent().remove();
}
}
}
话虽如此,但这不会使您快得多。 3500+元素是通过任何度量循环的许多元素。 分页结果。
您正在运行2个筛选器,然后访问每个筛选器的父级两次。
您是否可以这样做:
<ul>
<li id="1" class="test1"><div class="l1"><p>test1</p></div></li>
<li id="2" class="test2"><div class="l1"><p>test2</p></div></li>
<li id="3" class="test3"><div class="l1"><p>test3</p></div></li>
.... and so on
</ul>
要么
<ul>
<li id="1" data-text="test1"><div class="l1"><p>test1</p></div></li>
<li id="2" data-text="test2"><div class="l1"><p>test2</p></div></li>
<li id="3" data-text="test3"><div class="l1"><p>test3</p></div></li>
.... and so on
</ul>
这样,您可以在实际上要删除的LI上使用简单的选择器吗?
var remove = function remove(items){
$.each(items, function(index,value){
$('.'+value).remove();
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.