jQuery performance: hide() vs is(':visible') - which is faster?

后端 未结 3 468
故里飘歌
故里飘歌 2021-01-15 05:21

I have multiple dropdown boxes which drop when their link is clicked. The boxes have the possibility to overlap if they are open at the same time.

Is it faster to qu

相关标签:
3条回答
  • 2021-01-15 05:50

    I think its faster to hide it always. Another option could be to create a reference for the box example var b = $('#box2'). rather than calling $('#box2'). I think this would be the best option.

    0 讨论(0)
  • 2021-01-15 06:00

    You could use .toggle() function for this too.

    var $box1 = $('#box1'),
        $box2 = $('#box2');
    $('.majorDiv').on('click', '#box1-link', function(e){
    
      var $this = $(this);
      e.preventDefault();
    
      $box1.fadeToggle();
      $box2.slideDown(200, function(){
        //do stuff here
      });
    
    });
    
    0 讨论(0)
  • 2021-01-15 06:05

    Update

    (August 2013) It looks like with the changes to jQuery, simply calling hide may not be the fastest option anymore (though it's probably still preferable, for brevity, and clarity). Take a look at this updated benchmark test case.


    First, it should be noted that the runtime effect of this will be infinitesimal, and you would be hard-pressed to create a situation in which this would be the bottle-neck in your performance.

    The second approach, however, is likely to be faster simply because it already has that if check built-in to it anyway:

    // ... line 7996 (jQuery 1.8.1):
    if (!values[index] && display !== "none") {
        jQuery._data(elem, "olddisplay", display);
    }​
    // ...
    

    In other words, the function is only executed on the DOM element if it doesn't already have display: none. There's could still be a possibility that the .is() method manages to be a little faster since it avoids fewer method calls, but a look at the method itself will quickly dispel these fears:

    // ...line 6804:
    return !!selector && (
        typeof selector === "string" ?
            // If this is a positional/relative selector, check membership in the returned set
            // so $("p:first").is("p:last") won't return true for a doc with two "p".
            rneedsContext.test(selector) ?
                jQuery(selector, this.context).index(this[0]) >= 0 :
                jQuery.filter(selector, this).length > 0 : 
            this.filter(selector).length > 0);​
    // ...
    

    In short, the second is faster -- jsPerf test-case.

    0 讨论(0)
提交回复
热议问题