Jquery visible performance

I have a set of checkboxes on the page, and I only show a subset of these checkboxes at a time.

Then I perform some action that iterates over all the checkboxes and sees if they are checked or not:

eg.

$(".delete_items").click( function() {
     $('.checkboxes' ).each(function(){
     //do stuff
     }
}

Then I thought, well, since the user can never interact with hidden flags, the addition: visible to the flags will speed up the cycle

eg.

$(".delete_items").click( function() {
     $('.checkboxes :visible' ).each(function(){
     //do stuff
     }
}

But I do not know if: adds adds extra overhead. Any thoughts?

+3
source share
3 answers

:visible will add extra overhead since jQuery needs to check multiple properties regardless of whether the element is visible or not:

Elements can be considered hidden for several reasons:

  • They have no CSS display value.
  • = "".
  • 0.
  • , .

- : | API jQuery

, , -, DOM , .

, jQuery , getElementsByClass querySelectorAll.

, , .

.

Update:

$('.checkboxes.otherClass')

, :visible.

2:

jsPerf: http://jsperf.com/jquery-visible-test

, , , (Chrome 8, Mac OS X 10.6), :visible ~ 45% ( Firefox 3.6.13: 75% ).

3:

, .

+8

,

$('.checkboxes:visible') 

( ), , - , . , , ... .

, , , -. , , ( , ) .

+1

, . , querySelectorAll , .

, , , , . , , . jQuery jQuery.expr.filters.visible, $(this).is(':visible'):

$('.checkboxes' ).each(function(){
    if (this.checked && jQuery.expr.filters.visible(this)) {
        // checkbox is visible and checked
    }
}

Please note that although this works in jQuery 1.4.4, it is not documented and may change at any time ...

As other users have already noted, do not change your mind if you do not have significant performance issues. This solution may be useful if you are.

Edit A little benchmarking suggests that if your requirement should only work with checked, visible checkboxes, my solution is about two times faster than $('.checkboxes:visible')assuming that you do not have the appropriate class.

+1
source

Source: https://habr.com/ru/post/1785553/


All Articles