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

后端 未结 3 697
花落未央
花落未央 2021-01-13 02:55
$(preview-button).click(...)
$(preview-button).slide(...)
$(preview-button).whatever(...)

Is it a better practice to do this:

var p         


        
相关标签:
3条回答
  • 2021-01-13 03:41

    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( ... );
    
    0 讨论(0)
  • 2021-01-13 03:51

    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 讨论(0)
  • 2021-01-13 03:55

    Yes. You could also chain it:

    $(preview-button)
        .click(...)
        .slide(...)
        .whatever(...);
    
    0 讨论(0)
提交回复
热议问题