Is it faster to first check if an element exists, and then bind event handlers, like this:
if( $(\'.selector\').length ) {
$(\'.selector\').on(\'click\',
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
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.
$('.selector').on('click',function() { // Do stuff on click }
will bind if element exists otherwise not. So this is faster.
Just use
$('.selector').on('click',function() {
// Do stuff on click
}
If no elements exist with the class selector
, jQuery will simply not bind anything.
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.