Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performance overhead of event listeners on CSS classes used in JQuery code

If my markup looks like this:

<button id="button-1" class="nice">
<button id="button-2" class="nice">
<button id="button-3" class="nice">

and I define the following jQuery:

$(".nice").click(function () { 
    // something happens
});
  1. How many event listeners are established? 1 or 3?

  2. If I have 1000 buttons instead of 3, should I use event delegation instead?

  3. Is it best, performance-wise, to not define jQuery calls on classes of elements if those classes contain a large number of elements in the markup?

like image 751
fingerprint Avatar asked Jul 20 '09 03:07

fingerprint


People also ask

Does adding event listeners affect performance?

The results One <div> has 100 click handlers, and the click event is triggered by plain JS. This is interesting: When using native events, the number of listeners seems to degrade the performance faster than using jQuery.

What is an advantage of using event listeners in JavaScript?

Event listeners are among the most frequently used JavaScript structures in web design. They allow us to add interactive functionality to HTML elements by “listening” to different events that take place on the page, such as when the user clicks a button, presses a key, or when an element loads.

What is addEventListener jQuery?

The addEventListener() method allows you to add event listeners on any HTML DOM object such as HTML elements, the HTML document, the window object, or other objects that support events, like the xmlHttpRequest object.


1 Answers

1) 3 event listeners all pointing to the same function.

2) That depends on what you're trying to accomplish

3) Try doing some benchmarks, see where the performance hit becomes noticeable. I've had up to 1000 elements being selected then animated at the same time - and (in FF) the performance hit was unnoticeable up until about 600-700 elements. Performance of course depends on browser and JS engine. Some (Chrome) will be faster than others (IE). Its worth mentioning that for that site I used the same method as you have in your question.

like image 148
Darko Z Avatar answered Oct 11 '22 23:10

Darko Z