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');
//Recommend
$ele.on("click",function(){
}).fadeIn('slow').animate({height:'12px'},500);
8. Perform a large number of operations on DOM elements, separate them first and then append them
//Not recommended
var $container = $('#somecontainer');
var $ele = $container.first();
.....A series of complex operations
//Recommend
var $container = $('#somecontainer');
var $ele = $container.first().detach();
.....A series of complex operations
$container.append($ele);