提高jQuery性能优化的技巧

2020-05-19 07:39:37易采站长站整理

});
// 建议
$first.on(‘click’,function(){
    $first.css({
        ‘border’:’1px solid red’,
        ‘color’:’blue’
    });
});
// 糟糕
$first.click(function(){
    $first.css(‘border’,’1px solid red’);
    $first.css(‘color’,’blue’);
});
// 建议
$first.on(‘click’,function(){
    $first.css({
        ‘border’:’1px solid red’,
        ‘color’:’blue’
    });
});

链式操作
jQuery实现方法的链式操作是非常容易的。下面利用这一点。


// 糟糕
$second.html(value);
$second.on(‘click’,function(){
    alert(‘hello everybody’);
});
$second.fadeIn(‘slow’);
$second.animate({height:’120px’},500);
// 建议
$second.html(value);
$second.on(‘click’,function(){
    alert(‘hello everybody’);
}).fadeIn(‘slow’).animate({height:’120px’},500);

维持代码的可读性
伴随着精简代码和使用链式的同时,可能带来代码的难以阅读。添加缩紧和换行能起到很好的效果。


// 糟糕
$second.html(value);
$second.on(‘click’,function(){
    alert(‘hello everybody’);
}).fadeIn(‘slow’).animate({height:’120px’},500);
// 建议
$second.html(value);
$second
    .on(‘click’,function(){ alert(‘hello everybody’);})
    .fadeIn(‘slow’)
    .animate({height:’120px’},500);

选择短路求值
短路求值是一个从左到右求值的表达式,用 &&(逻辑与)或 || (逻辑或)操作符。


// 糟糕
function initVar($myVar) {
    if(!$myVar) {
        $myVar = $(‘#selector’);
    }
}
// 建议
function initVar($myVar) {
    $myVar = $myVar || $(‘#selector’);
}

选择捷径
精简代码的其中一种方式是利用编码捷径。


// 糟糕
if(collection.length > 0){..}
// 建议
if(collection.length){..}

繁重的操作中分离元素
如果你打算对DOM元素做大量操作(连续设置多个属性或css样式),建议首先分离元素然后在添加。