You must distinguish between binding events (attaching a callback to an event), and between actually processing the triggered events (calling/executing the callback). The first might occur only once per page, while the later might occur hundred of times depending on the user activity.
If you consider the event-binding only – which occurs on document ready (eventually) and each time the DOM changes (e.g. on Ajax Complete) – then using only one
.on()
call with only one callback is faster: http://jsperf.com/multiple-jquery-events/2If you consider the processing of the events being triggered – (i.e. the user clicks or mouse-overs
.myElement
) – then combining all events into one callback and differentiating them withif
statements is also faster than having multiple callbacks: http://jsperf.com/multiple-jquery-events/4
Here are some combined results from both tests:
The fastest to bind and also the fastest to process events:
$('#main').on('mouseenter mouseleave click', '.myElement', function(event) {
// Processing of the triggered event:
if (event.type == 'click') {
return false;
} else if (event.type == 'mouseenter') {
$(this).addClass('active');
} else if (event.type == 'mouseleave') {
$(this).removeClass('active');
}
});
The above code is the recommended syntax. The following examples are for information only.
About 30% slower to bind, and 50% slower to process the events:
$('#main').on('click', '.myElement', function(event) {
return false;
});
$('#main').on('mouseenter', '.myElement', function(event) {
$(this).addClass('active');
});
$('#main').on('mouseleave', '.myElement', function(event) {
$(this).removeClass('active');
});
The slowest to bind, and 70% slower to process the events:
$('#main').on({
mouseenter: function() {
$(this).addClass('active');
},
mouseleave: function() {
$(this).removeClass('active');
},
click: function() {
return false;
}
}, '.myElement');
About 25% slower to bind, and the slowest to process the events:
$('#main').on('click', '.myElement', function(event) {
return false;
});
$('#main').on('hover', '.myElement', function(event) {
$(this).addClass('active');
}, function() {
$(this).removeClass('active');
});
About 20% slower to bind, and 60% slower to process the events:
$('#main').on('click', '.myElement', function(event) {
return false;
}).on('mouseenter', '.myElement', function(event) {
$(this).addClass('active');
}).on('mouseleave', '.myElement', function(event) {
$(this).removeClass('active');
});