javascript – Is there a performance difference between on chained and on with multiple events?


I've always used on with multiple events with the thought that it would simplify my code and make it easier to understand, but for some time now I've come across several plugins using on in a chained way.

Example with multiple events:

$('#foo').on('click , dblclick', function(e) {
  if (e.type === 'click') {
  } else {
    console.log('double click');

Chained example:

$('bar').on('click', function() {
}).on('dblclick', function() {
  console.log('double click');

Analytically, is there any advantage/disadvantage of one approach to another? is there any case that would take one to be slower?


There is no performance difference, under the elem.addEventListener( type, eventHandler, false ); both versions become a simple elem.addEventListener( type, eventHandler, false ); for each event you pass (where type is the name of the event), so no matter what form, the amount of event listeners will be the same at the end. There is also the factor that there is a string break to identify that 'click dblclick' are two events, however even passing only one event as 'dblclick' this string processing occurs in the same way.

About approach advantage, it depends on the context. In your examples I think the second version is clearer in that it doesn't include an if-else , but that's subjective.

Note: actually there is a performance difference factor, its version with multiple events has ifs , however the cost of this is negligible.

Scroll to Top