开发者

Is referencing a selector faster in jquery than actually calling the selector? if so, how much does it make a difference?

$(preview-button).click(...)
$(preview-button).slide(...)
$(preview-button).whatever(...)

Is it a better practice to do this:

var preview-button = $(preview-button);
preview-button.click(...);
preview-button.click(...);
preview-button).slide(...);
preview-button.whatev开发者_运维问答er(...);

It probably would be better practice to do this for the sake of keeping code clean and modular, BUT does it make a difference performance wise? Does one take longer to process than the other? Thanks guys.


Yes it does, when you use the selector without storing it in a variable jQuery needs to parse the DOM EVERY TIME.

If you had something like $(".class") jQuery would need to find the elements with that class every time you use it but if it is stored in a variable it uses the unique identifier in the variable. No need to lookup.

So yeah i would totally recommend storing it into a variable.

UPDATE: Added chaining as an alternative.

If you only use the selector in one place you can also do chaining which means you add one method after another with the same dot notation like this:

$(".class")
       .click(function(){ ... })
       .mouseenter(function(){ ... })
       .css( ... );


Yes. You could also chain it:

$(preview-button)
    .click(...)
    .slide(...)
    .whatever(...);


It is much faster to use a named variable rather than passing jQuery a selector once for each action. However, as it was already mentioned, chaining is an optimal solution in most cases. You can see it for yourself. Here is a test I just did:

<script src="http://code.jquery.com/jquery-1.4.4.min.js" type="text/javascript"></script>
<script>
$(function(){
  //Try changing this value to see what happens as the number of nodes increases or decreases.
  for(i=1;i<2905;i++){
    $('body').append('<div id="'+i+'">'+i+'</div>')
  }
  //Case 1: Query the DOM once for each action
  var start = new Date().getTime();
  $('#2900').css('color','red');
  $('#2900').hide();
  $('#2900').show();
  $('#2900').html(new Date().getTime() - start);

  //Case 2: Chaining. Each method passed $('this') to the next one
  var start = new Date().getTime();
  $('#2901').css('color','blue').hide().show().html(new Date().getTime() - start);

  //Case 3: Use of a named variable
  var start = new Date().getTime();
  var a = $('#2902');
  a.css('color','green');
  a.hide();
  a.show();
  a.html(new Date().getTime() - start);

})
</script>

UPDATE:

Apparently Firefox does some kind of caching and the three cases perform very similarly. On the other side Chrome and Safari have a rather poor performance in Case 1, compared against cases 2 and 3 (especially as number or nodes increases).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜