有很多讨论jQuery和javascript性能的文章。然而,在这篇文章中,我计划总结一系列提供速度的建议来提高你的jQuery和javascript代码。当你准备用jQuery时,我强烈推荐遵循下面的规则:
1. 建立变量缓存(var caching)
DOM的遍历是相当费时间的,因此当你选择的元素计划重用他们时,一定要为他们建立缓存。
// bad code
h = $(‘#element‘).height();
$(‘#element‘).css(‘height‘,h-20);
// good code
$element = $(‘#element‘);
h = $element.height();
$element.css(‘height‘,h-20);
2. 避免全局变量(avoid
globals)
运用jQuery,和运用一般的javascript一样,最好确保你的变量在你的函数中拥有合适的范围。
// bad code
$element = $(‘#element‘);
h = $element.height();
$element.css(‘height‘,h-20);
// good code
var $element = $(‘#element‘);
var h = $element.height();
$element.css(‘height‘,h-20);
3. 应用匈牙利命名法(using hungarian
notation)
在变量的前面放置$符号使人很容易确认这个变量包含一个jQuery对象。
// bad
var first = $(‘#first‘);
var second = $(‘#second‘);
var value = $first.val();
// better - we use to put $ symbol before jQuery-manipulated objects
var $first = $(‘#first‘);
var $second = $(‘#second‘),
var value = $first.val();
4. 应用变量链(use var chaining)(单变量模式)
Rather than having multiple var statements, you can combine them into a single statement. I suggest placing any variables without assigned values at the end.
var
$first = $(‘#first‘),
$second = $(‘#second‘),
value = $first.val(),
k = 3,
cookiestring = ‘SOMECOOKIESPLEASE‘,
i,
j,
myArray = {};
5. 最好选择“on”(prefer ‘On‘)
Recent versions of jQuery have changed whereby
functions like click()
are shorthand
foron(‘click‘)
. In prior versions the implementation was different
whereby click()
what shorthand
for bind()
. As of jQuery 1.7, on()
is
the preferred method for attaching event handlers. However, for consistency you
can simply use on()
across the board.
// bad code
$first.click(function(){
$first.css(‘border‘,‘1px solid red‘);
$first.css(‘color‘,‘blue‘);
});
$first.hover(function(){
$first.css(‘border‘,‘1px solid red‘);
})
// better code
$first.on(‘click‘,function(){
$first.css(‘border‘,‘1px solid red‘);
$first.css(‘color‘,‘blue‘);
})
$first.on(‘hover‘,function(){
$first.css(‘border‘,‘1px solid red‘);
})
6. 使用链结构(use chaining)
Following on the above rule, jQuery makes it easy to chain mathods together. Take advantage of this.
// bad
$second.html(value);
$second.on(‘click‘,function(){
alert(‘hello everybody‘);
});
$second.fadeIn(‘slow‘);
$second.animate({height:‘120px‘},500);
// better
$second.html(value);
$second.on(‘click‘,function(){
alert(‘hello everybody‘);
}).fadeIn(‘slow‘).animate({height:‘120px‘},500);
7. 保持代码的可读性(keep your code readable)
When trying to condense your scripts and utilize chaining, code can sometimes become unreadable. Try to utlize tabs and new lines to keep things looking pretty.
// bad code
$second.html(value);
$second.on(‘click‘,function(){
alert(‘hello everybody‘);
}).fadeIn(‘slow‘).animate({height:‘120px‘},500);
// better code
$second.html(value);
$second
.on(‘click‘,function(){ alert(‘hello everybody‘);})
.fadeIn(‘slow‘)
.animate({height:‘120px‘},500);
8. 使用短路循环(Prefer
Short-circuiting)
Short-curcuit
evaluation are expressions evaluated from left-to-right and use
the &&
(logical and)
or ||
(logical or) operators.
// bad code
function initVar($myVar) {
if(!$myVar) {
$myVar = $(‘#selector‘);
}
}
// better code
function initVar($myVar) {
$myVar = $myVar || $(‘#selector‘);
}
9. 使用简写(prefer shortcuts)
One of the ways to condense your code is to take advantage of coding shortcuts.
// bad
if(collection.length > 0){..}
// better
if(collection.length){..}
10. 对元素进行大量操作时应选择拆卸(detach elements when doing heavy manipulations)
if you are going to do heavy manupipulation of a DOM element, it is recommended that you first detach it and then re-append it.
// bad code
var
$container = $("#container"),
$containerLi = $("#container li"),
$element = null;
$element = $containerLi.first();
//... a lot of complicated things
// better code
var
$container = $("#container"),
$containerLi = $container.find("li"),
$element = null;
$element = $containerLi.first().detach();
//...a lot of complicated things
$container.append($element);
11. 知道技巧(know the tricks)
When using methods within jQuery that you may have less experience with, be sure to check the documentation as there may be a preferable or faster way to use it.
// bad
$(‘#id‘).data(key,value);
// better (faster)
$.data(‘#id‘,key,value);
12. 使用子查询缓存父元素(use subqueries caching parents)
As mentioned earlier, DOM traversal is an expensive operation. It is typically better to cache parent elements and reuse these cached elements when selecting child elements.
// bad
var
$container = $(‘#container‘),
$containerLi = $(‘#container li‘),
$containerLiSpan = $(‘#container li span‘);
// better (faster)
var
$container = $(‘#container ‘),
$containerLi = $container.find(‘li‘),
$containerLiSpan= $containerLi.find(‘span‘);
13. 避免通用选择器(avoid universal selectors)
When combined with other selectors, the universal selector is extremely slow.
// bad
$(‘.container > *‘);
// better
$(‘.container‘).children();
14. 避免默认通用选择器(avoid implied universal selectors)
When you leave off the selector, the universal
selector (*
) is still implied.
// bad
$(‘.someclass :radio‘);
// better
$(‘.someclass input:radio‘);
15. 优化选择器(optimize selectors)
for example, using an ID should already be sufficiently specific, so there is no need to add additional selector specificity.
// bad
$(‘div#myid‘);
$(‘div#footer a.myLink‘);
// better
$(‘#myid‘);
$(‘#footer .myLink‘);
16. 不要担心多个IDs(Dont descend mutiple IDs)
Again, when used properly, ID’s should be sufficiently specific not to require the additional specificity of multiple descendant selectors.
// bad
$(‘#outer #inner‘);
// better
$(‘#inner‘);
17. 不要用废弃的方法(Dont use deprecated Methods)
It is important to always keep an eye on deprecated methods for each new version and try avoid using them.
// bad - live is deprecated
$(‘#stuff‘).live(‘click‘, function() {
console.log(‘hooray‘);
});
// better
$(‘#stuff‘).on(‘click‘, function() {
console.log(‘hooray‘);
});
18. 从内容发布网络上加载jQuery code
The Google CDN quickly delivers the script from the user’s nearest cache location. To use the Google CDN, use the following url for this http://code.jQuery.com/jQuery-latest.min.js