Jquery,JavaScript性能优化

本文介绍了一系列提高jQuery代码效率的方法,包括缓存DOM元素、避免使用全局变量、采用匈牙利命名法、使用单Var模式、利用'on'方法绑定事件、简化JavaScript代码、链式调用等技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


一、缓存变量,减少DOM的遍历
h = $('#element').height();
$('#element').css('height',h-20);
优化↓↓↓↓↓↓↓↓↓↓↓

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


二 、避免全局变量


jQuery与javascript一样,一般来说,最好确保你的变量在函数作用域内。


三、使用使用匈牙利命名法

(建议 - 在jQuery对象前加$前缀)
var first = $('#first');
var second = $('#second');
var value = $first.val();
 优化↓↓↓↓↓↓↓↓↓↓↓
var $first = $('#first');
var $second = $('#second'),
var value = $first.val();

四、使用 Var 链(单 Var 模式)
var
  $first = $('#first'),
  $second = $('#second'),
  value = $first.val(),
  k = 3,
  cookiestring = 'SOMECOOKIESPLEASE',
  i,
  j,
  myArray = {};

五、请使用’On’
$first.click(function(){
    $first.css('border','1px solid red');
    $first.css('color','blue');
});
$first.hover(function(){
    $first.css('border','1px solid red');
})
 优化↓↓↓↓↓↓↓↓↓↓↓
$first.on('click',function(){
    $first.css('border','1px solid red');
    $first.css('color','blue');
})
$first.on('hover',function(){
    $first.css('border','1px solid red');
})

六、精简javascript
$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'
    });
});

七、链式操作
$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){..}

十一、使用子查询缓存的父元素
var
    $container = $('#container'),
    $containerLi = $('#container li'),
    $containerLiSpan = $('#container li span');
      优化↓↓↓↓↓↓↓↓↓↓↓
var
    $container = $('#container '),
    $containerLi = $container.find('li'),
    $containerLiSpan= $containerLi.find('span');

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值