I'm reading code of my collegues and I'm wondering if the performance could be improved. For any button-event there is code like that:
a)
$("body").on("click", ".aButtonName", function() { ....});
$("body").on("click", ".aButtonName", function() { ....});
$("body").on("click", ".aButtonName", function() { ....});
....
$("body").on("click", ".aButtonName", function() { ....});
b) Would it be faster to analyse each target-event, after the body is clicked:
$(document.body).on('click', function( e ){
var trg = $(e.target).closest('button');
if(!trg || !trg.attr('class'))
return;
if ( trg.attr('class').indexOf('my_button') > -1) {
....
It would most likely reduce performance. In the second scenario, you end up executing the callback function, passing parameters, and performing several DOM interactions just to exit. In the first, jQuery performs a selector match and only executes the function if there is a match.
In both styles, the event is handled once it "bubbles up" (propagates) to the body
. This "delegate-style" checks to see if the selector matches the target (or a parent).
As others suggest, caching the $("body")
would save a number of DOM queries and you could get better performance by using a closer/smaller delegate than body
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With