jQuery性能优化11条(二)
(2011-12-23 14:37:29)
标签:
jquery性能优化it |
分类: jquery那些事 |
3、缓存jQuery对象
养成保存jQuery对象到一个变量上(就像上面的例子)的习惯。例如,不要这样做:
-
$('#traffic_light
input.on).bind(' click',function(){...}); -
$('#traffic_light
input.on).css(' border',' 3pxdashed yellow'); -
$('#traffic_light
input.on).css(' background-color',' orange'); -
$('#traffic_light
input.on).fadeIn(' slow');
取而代之,首现保存jQuery变量到一个本地变量后,再继续你的操作。
-
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');
提示:使用$前辍表示我们的本地变量是一个jQuery包集。记住,不要在你的应该程序里出现一次以上的jQuery重复的选择操作。
如果你想在你的程序的其它地方使用jQuery结果对象(result
object(s)),或者你的函数要执行多次,要把它缓存在一个全局范围的对象里。通过定义一个全局容器保存jQuery结果对象,就可以在其它的函数里引用它。
-
//
Define an object in the global scope (i.e. the window object) -
window.$my
={ -
// Initialize all the queries you want to use more than once -
head : $('head'), -
traffic_light : $('#traffic_light'), -
traffic_button : $('#traffic_button')}; -
function
do_something(){ -
// Now you can reference the stored results and manipulate them -
var script 'script');= document.createElement_x( -
$my.head.append(script); -
// When working inside functions, continue to save jQuery results -
// to your global container. -
$my.cool_results = $('#some_ul li' ); -
$my.other_results = $('#some_table td' ); -
// Use the global functions as you would a normal jQuery result -
$my.other_results.css('border-color', 'red'); -
$my.traffic_light.css('border-color', 'green'); -
}
4、更好的利用链
-
var
$active_light '#traffic_light= $( input.on' ); -
$active_light.bind('click',
function(){...}) -
.css('border', '3px dashed )yellow' -
.css('background-color', 'orange') -
.fadeIn('slow');
这样可以让我们写更少的代码,使JavaScript更轻量。
5、使用子查询
jQuery允许我们在一个包集上附加其它的选择器。因为我们已经在本地变量里保存了父对象这样会减少以后在选择器上的性能开销。
-
<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>
例如,我们可以利用子查询缓存active和inactive
lights以便后面的操作。
-
var
$traffic_light '#traffic_light'),= $( -
$active_light
= $traffic_light.find('input.on'), -
$inactive_lights
= $traffic_light.find('input.off');
提示:可以用逗号隔开一次定义多个本地变量,这样可以节省一些字节。
前一篇:jQuery性能优化11条(一)
后一篇:jQuery性能优化11条(三)