9-bits
9-bits

Reputation: 10765

Will attaching multiple JS click handlers slow down a page?

I have possibly 200 click handlers that I have to attach on a page. (I'm unable to delegate them because they are associated with a jQuery plugin that needs to be on the individual element)

I'm wondering if attaching so many click handlers will slow down performance?

I know that mouseover / scroll handlers are potentially fired many times and can slow down the page - however click handlers are fired less often, but does just having them 'listen' slow down the page?

Upvotes: 0

Views: 3077

Answers (3)

jfriend00
jfriend00

Reputation: 707228

If you have 200 click handlers each attached to a different object, the only place that this will slow you down a bit is attaching the 200 event handlers. Once they are attached, the individual clicks will be no different whether there are 200 event handlers on 200 separate objects or 1 event handler on 1 object.

If you had 200 click handlers all on the same object, then you could see a slow-down when the click was processed on that object because it would have to make 200 function calls to execute all 200 event handlers.

So, as long as they are all on separate objects, the only slow-down would be initially attaching the event handlers. Once they are attached, there is no performance impact.

Upvotes: 4

joidegn
joidegn

Reputation: 1068

of course event handlers dont come totally free, however, they are quite cheap. The question is what the events associated with the handlers do. Usually rendering of elements, animations etc take a lot more of a performance toll from browsers.

Also, there is a difference between how the event listeners are implemented. See for example this post

Upvotes: 1

Andrei G
Andrei G

Reputation: 1590

No it doesn't.

You are right, the mouseover handlers could potentially get fired a lot, but the simple fact of having listeners attached to events does not slow down the page.

However if you have 200 listeners on one single event (which is very improbable) that might slow you down when the event is triggered. Again, I don't think this is the case.

Upvotes: 3

Related Questions