2010-03-24 09:38:50| 分类: javascript | 标签: |字号大中小 订阅
From : 2009/04/jquery-performance-rules/
On
The fastest selector in jQuery is the ID selector (
<div id="content">
<form method="post" action="">
<h2>Traffic Light</h2>
<ul id="traffic_light">
<li><input type="radio" class="on" name="light" value="red" /> Red</li>
<li><input type="radio" class="off" name="light" value="yellow" /> Yellow</li>
<li><input type="radio" class="off" name="light" value="green" /> Green</li>
</ul>
<input class="button" id="traffic_button" type="submit" value="Go" />
</form>
</div>
Selecting the button like this is slower:
var traffic_button = $('#content .button'); Instead, select the button directly:
var traffic_button = $('#traffic_button'); On
var traffic_lights = $('#traffic_light input'); The second fastest selector in jQuery is the Tag selector (
.
<div id="content">
<form method="post" action="">
<h2>Traffic Light</h2>
<ul id="traffic_light">
<li><input type="radio" class="on" name="light" value="red" /> Red</li>
<li><input type="radio" class="off" name="light" value="yellow" /> Yellow</li>
<li><input type="radio" class="off" name="light" value="green" /> Green</li>
</ul>
<input class="button" id="traffic_button" type="submit" value="Go" />
</form>
</div>
Always prefix a class with a tag name (and remember to descend from an ID):
var active_light = $('#traffic_light input.on'); Note: The class selector is among the slowest selectors in jQuery; in IE it loops through the entire DOM. Avoid using it whenever possible. Never prefix an ID with a tag name. For example, this is slow because it will loop through all
var content = $('div#content'); Along the same lines, it is redundant to descend from multiple IDs:
var traffic_light = $('#content #traffic_light'); Get in the habit of saving your jQuery objects to a variable (much like our examples above). For example, never (eeeehhhhver) do this:
$('#traffic_light input.on).bind('click', function(){});
$('#traffic_light input.on).css('border', '3px dashed yellow');
$('#traffic_light input.on).css('background-color', 'orange');
$('#traffic_light input.on).fadeIn('slow'); Instead, first save the object to a local variable, and continue your operations:
var $active_light = $('#traffic_light input.on');
$active_light.bind('click', function(){});
$active_light.css('border', '3px dashed yellow');
$active_light.css('background-color', 'orange');
$active_light.fadeIn('slow'); Tip: Since we want to remember that our local variable is a jQuery wrapped set, we are using $ as a prefix. Remember, never repeat a jQuery selection operation more than on