Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - performance of element detection

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) {
  ....
like image 338
user2952265 Avatar asked Nov 11 '22 12:11

user2952265


1 Answers

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.

like image 156
Sam R Avatar answered Nov 14 '22 22:11

Sam R