Abdelouahed EL HARIRI
Abdelouahed EL HARIRI

Reputation: 305

Is it better to use many event delegation with jQuery or just on and use if inside?

I'm working on a new website based on jquery and i was wondering which is the best option regarding performance :

Option 1:

$("body").on("click",".label-type1",function(){...});
$("body").on("click",".label-type2",function(){...});
....

Option 2:

$("body").on("click","label",function(){
     if($(this).hasClass("label-type1"){
        ...
     }else if($(this).hasClass("label-type2"){
        ...
     }});

Thank you in advance.

Upvotes: 2

Views: 34

Answers (1)

Cleod9
Cleod9

Reputation: 103

Between these two options, you should find the performance difference fairly negligible since both handlers are going through a similar process to filter by the labels you are trying to target.

See jQuery source code for events and matching selectors:

https://github.com/jquery/jquery/blob/master/src/event.js#L395

https://github.com/jquery/jquery/blob/2d4f53416e5f74fa98e0c1d66b6f3c285a12f0ce/src/selector-native.js#L143

And a related performance test for native matchesSelector():

https://jsperf.com/matchesselector-performance

Option 1 will have more event handlers created of course, which means more memory usage. But that doesn't necessarily mean it's going to impact performance until you scale drastically. That being said, option 1 should perform slightly better at a small scale since it's not going through additional hasClass conditions inside the handlers. But option 2 is much better if you're concerned about keeping memory footprint low, and may be easier to organize since you can create a helper function to handle each case in a separate place in your code.

Upvotes: 1

Related Questions