1. DOM traversal is expensive, so cache variables.
//Not recommended
var h = $('#ele').height();
$('#ele').css('height', h-20);
//Recommend
var $ele = $('#ele');
var h = $ele.height();
$ele.css('height',h-20);
2. Optimize selectors.
//Not recommended
$('div#myid')
//Recommend
$('#myid')
3. Avoid implicit universal selectors.
//Not recommended
$('.someclass :radio')
//Recommend
$('.someclass input:radio')
4. Avoid universal selectors.
//Not recommended
$('.container > *')
//Recommend
$('.container').children()
5. Keep the code as simple as possible.
//Not recommended
if(arr.length > 0){}
//Recommended
if(arr.length){}
6. Merge functions as much as possible.
//Not recommended
$f.on("click", function(){
$(this).css('border','1px solid red');
$(this).css('color','blue');
});
//Recommend
$f.on("click", function(){
$(this).css({
'border':'1px solid red',
'color': 'blue'
});
});
7. Use chain operations as much as possible.
//Not recommended
$ele.html();
$ele.on("click",function(){});
$ele.fadeIn('slow');
//おすすめ
$ele.on("クリック",function(){
}).fadeIn('slow').animate({height:'12px'},500);
8. DOM 要素に対して多数の操作を実行し、最初に要素を分割してから追加します
// 推奨されません
var $container = $('#somecontainer');
var $ele = $container.first();
……一連の複雑な操作
//おすすめ
var $container = $('#somecontainer');
var $ele = $container.first().detach();
……一連の複雑な操作
$container.append($ele);