Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

javascript - In jQuery, is it faster to check if an element exists before trying to bind event handlers?

Is it faster to first check if an element exists, and then bind event handlers, like this:

if( $('.selector').length ) {
    $('.selector').on('click',function() {
          // Do stuff on click
    }
}

or is it better to simply do:

$('.selector').on('click',function() {
     // Do stuff on click
}

All this happens on document ready, so the less delay the better.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

A better way to write the if check is like this

var elems = $('.selector');
if( elems.length ) {
    elems.on('click',function() {
          // Do stuff on click
    });
}

So let us test this and see what the code tells us http://jsperf.com/speed-when-no-matches

Showing performance without elements

In the end you are talking milliseconds of difference and the non if check is not going to be noticeable when run once. This also does not take into account when there are elements to find, than in that case, there is an extra if check. Will that check matter

So let us look when they find elements http://jsperf.com/speed-when-has-matches

There is really no difference. So if you want to save fractions of a millisecond, do the if. If you want more compact code, than leave it the jQuery way. In the end it does the same thing.

Showing performance with elements


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...