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.
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.
Share Improve this question asked Feb 24, 2014 at 13:40 NiclasNiclas 1,4021 gold badge12 silver badges25 bronze badges 6 | Show 1 more comment4 Answers
Reset to default 13A 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
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.
Just use
$('.selector').on('click',function() {
// Do stuff on click
}
If no elements exist with the class selector
, jQuery will simply not bind anything.
$('.selector').on('click',function() { // Do stuff on click }
will bind if element exists otherwise not. So this is faster.
Use the binding directly.
$('selector').on('click',function() {
// Do stuff on click
}
If if there are no elements with the specified selector, it won't do anything - not even post an error, which means that actual check for the element would be doing the same thing twice. I wouldn't call it exactly a check of the existence of an element, but the way this is implemented in jQuery certainly acts that way.
if( $('.selector').length ) { $('.selector').on('click',function() { // Do stuff on click } }
will be much slower because the selector is evaluated twice.... if you cache it I don't think it will make much difference – Arun P Johny Commented Feb 24, 2014 at 13:41