1

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

  • There is the only one <div class="cool-div"> on the page.

Situation 2

  • There are many <div class="cool-div"> on the page.
4
  • Definetely direct.
    – user7209780
    Commented Jan 7, 2017 at 19:08
  • click is a shortcut for .on( "click", handler ), direct would be faster. to learn more api.jquery.com/click
    – azs06
    Commented Jan 7, 2017 at 19:14
  • Because those 1-2 milliseconds in difference will change anything
    – Andreas
    Commented Jan 7, 2017 at 19:19
  • I don't know, I would have to test. But I usually prefer b) because I don't have to wait for DOMContentLoaded for my scripts to work. So even if the page is not finished loading my buttons already work.
    – BrunoLM
    Commented Jan 7, 2017 at 19:25

2 Answers 2

1

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,

0

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.

Not the answer you're looking for? Browse other questions tagged or ask your own question.