// Bad: This runs three functions before it
// realizes there's nothing in the selection
$( "#nosuchthing" ).slideUp();// Better:
var $mySelection = $( "#nosuchthing" );
if ( $mySelection.length ) {
$mySelection.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 部件。
5. Optimize Selectors
选择器的优化和过去比起来并不是那么的重要,因为很多浏览器都实现了 document.querySelectorAll() 方法并且jQuery将选择器的负担转移到了浏览器上面。但是仍然有一些技巧需要铭记在心。
基于ID的选择器
以一个ID作为选择器的开始总是最好的。
// Fast:
$( "#container div.robotarm" ); // Super-fast:
$( "#container" ).find( "div.robotarm" );
采用 .find() 方法的方式将更加的快速,因为第一个选择器已经过处理,而无需通过嘈杂的选择器引擎 — ID-Only的选择器已使用 document.getElementById() 方法进行处理,之所以快速,是因为它是浏览器的原生方法。
特异性
尽量详细的描述选择器的右侧,对于左侧则应反其道而行之。
// Unoptimized:
$( "div.data .gonzalez" );// Optimized:
$( ".data td.gonzalez" );
尽量在选择器的最右侧使用 tag.class 的形式来描述选择器,而在左侧则尽量只使用 tag 或者 .class 。
避免过度使用特异性
$( ".data table.attendees td.gonzalez" ); // Better: Drop the middle if possible.
$( ".data td.gonzalez" );
去讨好“DOM”总是有利于提升选择器的性能,因为选择器引擎在搜寻元素时无需进行太多的遍历。
避免使用通用选择器
如果一个选择器明确或暗示它能在不确定的范围内进行匹配将会大大影响性能。
$( ".buttons > *" ); // Extremely expensive.
$( ".buttons" ).children(); // Much better. $( ".category :radio" ); // Implied universal selection.
$( ".category *:radio" ); // Same thing, explicit now.
$( ".category input:radio" ); // Much better.
复制代码
6. Use Stylesheets for Changing CSS on Many Elements
假如你使用 .css() 方法来改变超过20个元素的CSS,应当考虑为页面添加一个样式标签作为替代,这样做可以提升将近60%的速度。










