Reputation: 10227
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
<div class="cool-div">
on the page.Situation 2
<div class="cool-div">
on the page.Upvotes: 1
Views: 86
Reputation: 5534
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.
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
If you don't have the time to read the article above, the following guildelines are to be considered :
input.focus()
causes reflow.
Hope it helps,
best regards,
Upvotes: 1
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