您的位置:首页 > Web前端 > JQuery

Jquery,JavaScript性能优化

2017-02-13 11:19 399 查看
优化↓↓↓↓↓↓↓↓↓↓↓

二 、避免全局变量

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('
bafa
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');
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: