发布于: 性能

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

如果你尝试在一个空的选取结果上运行大量代码,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 部件(widgets),即使选取结果中不包含元素,这些部件也会产生大量的开销。