发布在:性能

不要对不存在的元素执行操作

jQuery 不会告诉你是否尝试对一个空选择运行大量代码 - 它会继续执行,好像没有任何问题。由你来验证你的选择是否包含一些元素。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// Bad: This runs three functions before it
// realizes there's nothing in the selection
$( "#nosuchthing" ).slideUp();
// Better:
var elem = $( "#nosuchthing" );
if ( elem.length ) {
elem.slideUp();
}
// Best: Add a doOnce plugin.
jQuery.fn.doOnce = function( func ) {
this.length && func.apply( this );
return this;
}
$( "li.cartitems" ).doOnce(function() {

// make it ajax! \o/
});

此指导特别适用于 jQuery UI 小部件,即使选择不包含元素,它们也会有很大的开销。