Date

Cache

(From: http://modernweb.com/2013/11/25/writing-better-jquery-code/) DOM的遍历很耗费时间,因此最好是将重复使用的元素缓存下来。

// bad

h = $('#element').height();
$('#element').css('height',h-20);

// good

$element = $('#element');
h = $element.height();
$element.css('height',h-20);

// bad

var 
    $container = $('#container'),
    $containerLi = $('#container li'),
    $containerLiSpan = $('#container li span');

// better (faster)

var 
    $container = $('#container '),
    $containerLi = $container.find('li'),
    $containerLiSpan= $containerLi.find('span');

Detach Elements when doing heavy manipulations

(From: http://modernweb.com/2013/11/25/writing-better-jquery-code/) 这里不清楚为什么这么做。detach 和remove不同的就是其会将和element对应的data和event handler保存下来。当之后被detach的元素又被append到原来的位置时,就恢复了原来的状态。但是为什么在进行元素进行大量操作之前要将其detach呢?

// bad

var 
    $container = $("#container"),
    $containerLi = $("#container li"),
    $element = null;

$element = $containerLi.first(); 
//... a lot of complicated things

// better

var 
    $container = $("#container"),
    $containerLi = $container.find("li"),
    $element = null;

$element = $containerLi.first().detach(); 
//...a lot of complicated things

$container.append($element);

保持可读性

1.多用链式操作

// 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);

2. 缩进的使用

// bad

$second.html(value);
$second.on('click',function(){
    alert('hello everybody');
}).fadeIn('slow').animate({height:'120px'},500);

// better

$second.html(value);
$second
    .on('click',function(){ alert('hello everybody');})
    .fadeIn('slow')
    .animate({height:'120px'},500);

Short-Circuit Evaluation

(From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators#Short-Circuit_Evaluation)

// bad

function initVar($myVar) {
    if(!$myVar) {
        $myVar = $('#selector');
    }
}

// better

function initVar($myVar) {
    $myVar = $myVar || $('#selector');
}

这个技巧不单单是在javascript里面了,很多语言都适用

当需要用循环(for)的时候想一想有没有另外已有的办法?

//1. join string
var arr = ['item1','item2','item3'];
var list = '<ul><li>' + arr.join('</li><li>') + '</li></ul>';

//2. transverse array
$.each(arr,function(index,value){
    //to do something
});