首页 > Web开发 > 详细

编写更好的jQuery代码

时间:2014-01-20 19:37:20      阅读:448      评论:0      收藏:0      [点我收藏+]

有很多讨论jQuery和javascript性能的文章。然而,在这篇文章中,我计划总结一系列提供速度的建议来提高你的jQuery和javascript代码。当你准备用jQuery时,我强烈推荐遵循下面的规则:

1. 建立变量缓存(var caching)

DOM的遍历是相当费时间的,因此当你选择的元素计划重用他们时,一定要为他们建立缓存。

bubuko.com,布布扣
// bad code
h = $(‘#element‘).height();
$(‘#element‘).css(‘height‘,h-20);

// good code
$element = $(‘#element‘);
h = $element.height();
$element.css(‘height‘,h-20);
bubuko.com,布布扣

2. 避免全局变量(avoid globals)
运用jQuery,和运用一般的javascript一样,最好确保你的变量在你的函数中拥有合适的范围。

bubuko.com,布布扣
// 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);
bubuko.com,布布扣

3. 应用匈牙利命名法(using hungarian notation)
在变量的前面放置$符号使人很容易确认这个变量包含一个jQuery对象。

bubuko.com,布布扣
// 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();
bubuko.com,布布扣

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.

bubuko.com,布布扣
var 
  $first = $(‘#first‘),
  $second = $(‘#second‘),
  value = $first.val(),
  k = 3,
  cookiestring = ‘SOMECOOKIESPLEASE‘,
  i,
  j,
  myArray = {};
bubuko.com,布布扣

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.

bubuko.com,布布扣
// 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‘);
})
bubuko.com,布布扣

6. 使用链结构(use chaining)

Following on the above rule, jQuery makes it easy to chain mathods together. Take advantage of this.

bubuko.com,布布扣
// 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);
bubuko.com,布布扣

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.

bubuko.com,布布扣
// 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);
bubuko.com,布布扣

8. 使用短路循环(Prefer Short-circuiting)
Short-curcuit evaluation are expressions evaluated from left-to-right and use the &&(logical and) or || (logical or) operators.

bubuko.com,布布扣
// bad code
function initVar($myVar) {
    if(!$myVar) {
        $myVar = $(‘#selector‘);
    }
}

// better code
function initVar($myVar) {
    $myVar = $myVar || $(‘#selector‘);
}
bubuko.com,布布扣

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.

bubuko.com,布布扣
// 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);
bubuko.com,布布扣

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.

bubuko.com,布布扣
// bad
var 
    $container = $(‘#container‘),
    $containerLi = $(‘#container li‘),
    $containerLiSpan = $(‘#container li span‘);

// better (faster)
var 
    $container = $(‘#container ‘),
    $containerLi = $container.find(‘li‘),
    $containerLiSpan= $containerLi.find(‘span‘);
bubuko.com,布布扣

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.

bubuko.com,布布扣
// bad
$(‘div#myid‘); 
$(‘div#footer a.myLink‘);

// better
$(‘#myid‘);
$(‘#footer .myLink‘);
bubuko.com,布布扣

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.

bubuko.com,布布扣
// bad - live is deprecated
$(‘#stuff‘).live(‘click‘, function() {
  console.log(‘hooray‘);
});

// better
$(‘#stuff‘).on(‘click‘, function() {
  console.log(‘hooray‘);
});
bubuko.com,布布扣

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

 

编写更好的jQuery代码

原文:http://www.cnblogs.com/jassonfish/p/3526808.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!