I was recently writing a blog post about checking if jquery elements exist before binding event handlers, I did a quick jsfiddle which you can see here
The thing I dont understand, is that the results show (using chrome to measure in microseconds) that test 2 is a lot faster then test 1.
You’ll see from the jsfiddle that test 2 checks the existent of the matching before binding a click event
TEST 1 is:
console.time('time_1');
$('.yep').click(function() {
alert('clicked');
});
console.timeEnd('time_1');
test 1 just tried to bind the event
TEST 2:
console.time('time_2');
if ($('.yep').length) {
$('.yep').click(function() {
alert('clicked');
});
}
console.timeEnd('time_2');
test 2 check the element exists before binding.
I am running the two bits of code on some, 87 I think ‘section’ elemenets, one of which has a class of ‘yep’
I cant really see why the second test is faster, as its doing more work.
results:
time_1: 0.856ms
time_2: 0.146ms
Can anyone shed some light and help out a confused developer.
thanks
n.b please dont reply with alternative ways to bind click events in jquery, the .click is just used as a simple test
The primary thing going on here is that the first time you query a selector, the engine has to do more work than subsequent queries, which can sometimes be cached. If you reverse the first two tests, you’ll find that whichever one runs first tends to be the slower one.
Despite that, and mostly as a side note, in test 2 you’re querying the DOM twice, first to check the
length, and then to hook up the handler. If the query is cached it doesn’t matter much, but still, just do it once:Note, though, that calling
clickon a jQuery set with no elements in it is a harmless no-op (not an error or anything), so there’s no need for thelengthcheck unless you’re also doing something else you haven’t shown.