Consider the following code:
$('div').click(function(){
$(this).animate({height:100}, 500)
$(this).css({opacity:1});
});
Versus:
$('div').click(function(){
$(this).animate({height:100}, 500);
})
.click(function(){
$(this).css({opacity:1});
});
Does jQuery or JavaScript essentially “compile” the second code sample into something like the first rather than maintaining two separate event handlers? I ask about whether jQuery or JavaScript does this because I’d also be interested to know if such “compilation” is a feature of native JS or something implemented by jQuery.
It seems to me that this “compilation” is not actually done, at least not in a way that eliminates the differences between the two code samples. Using JSPerf, I compared the speed between each one and it appears that the first code sample is substantially faster.
Handlers are fired in the order they are bound and each
$('div').click()binds another handler to the element in question. In your case the first one only binds 1 event handler and thus performs faster because it only fires one event. The second binds two event handlers, and thus is slower because it fires two events instead of one (more overhead).