最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Will attaching multiple JS click handlers slow down a page? - Stack Overflow

programmeradmin3浏览0评论

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?

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?

Share edited Nov 27, 2022 at 10:29 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Feb 24, 2012 at 13:47 9-bits9-bits 10.8k21 gold badges63 silver badges84 bronze badges 1
  • 1 Sounds like it could be worth re-factoring the jQuery plugin to utilise event delegation. – Simon Smith Commented Feb 24, 2012 at 13:53
Add a ment  | 

3 Answers 3

Reset to default 4

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.

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.

of course event handlers dont e 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

发布评论

评论列表(0)

  1. 暂无评论