GProst
GProst

Reputation: 10227

Which jQuery .on() is faster: direct or delegated?

Assume I need to set up 'click' event listener on <div class="cool-div">. And let's say it has an ancestor.

<div class="cool-ancestor">
    ...
    <div class="cool-div">
    ...
</div>

Which of the following code I should use for better performance and why?

a) $(document).on('click', '.cool-div', function(){...})

b) $('.cool-ancestor').on('click', '.cool-div', function(){...})

c) $('.cool-div').on('click', function(){...})

Situation 1

Situation 2

Upvotes: 1

Views: 86

Answers (2)

boehm_s
boehm_s

Reputation: 5534

REMOVE JQUERY

If you're intressted in performance, removing jquery is the first thing to do. Just enjoy Vanilla-JS performance. JQuery is slower when it comes to select elements, that's a thing, but another reason to hate JQuery is that it automatically attaches event listeners to certains elements.
For example, if you use jquery 1.11, all you a tags will have a blur and a focus event listener setted.

HOW DOES THE DOM WORK ?

If you want to build powerful apps in the navigator, you need to know how the navigator deals with your code.
So, here is a wonderful article about DOM events
reflow and repaints
And a good ressource about what will call a reflow

SOME GUIDELINES

If you don't have the time to read the article above, the following guildelines are to be considered :

  • Keep yout HTML light (the less nested elements you have, the faster events will run through your page)
  • Do not attach useless event listeners, it will just consume ressources for no reason (so -again - remove jQuery).
  • Try to not trigger reflow because the positions and dimensions of all the elements will be recalculated. For example, CSS position changes or input.focus() causes reflow.


Hope it helps, best regards,

Upvotes: 1

jaya chandra
jaya chandra

Reputation: 52

If your code doesn't generate any child div's

     <div class="cool-div">

Dynamically then direct is perfect and works smoothly. Else it's better to use delegated as in sometimes direct may not work for dynamically generated elements.

Upvotes: 0

Related Questions