First off, here's a similar question/answer with some pertinent info to understanding this issue: Should all jquery events be bound to $(document)?.
Here are some notes on large numbers of event handlers and performance:
- 30+ is NOT a large number of event handlers. In most cases, you shouldn't have to worry about 30+ event handlers at all (see possible exception below if you have nasty selectors).
- If event handlers are attached directly to the intended object (the most efficient way for them to be processed at the actual event time), you will maximize your run-time performance.
- If you are using delegated event handling, then event handlers should be placed on a parent that is as close as possible to the actual object receiving the event. Putting all delegated event handlers on a top level object like
document
or document.body
is generally a bad idea because that makes the code have to look at more selectors for every event than if the event handlers are closer to the actual object that triggers the event thus avoiding evaluating most of the selectors for most events.
- If you are using delegated event handling, then the performance of the secondary selector (the 2nd argument to
.on()
) is important. If this is a complicated selector that is not fast to evaluate and you have a lot of these all attached to the same object for the same event, you could start to see some performance degradation. How much performance degradation will depend upon the exact circumstances.
So, the worst case is if you have a lot of delegated event handlers all attached to the same object that all have a complicated secondary selector. This is the worst case because the event will have to bubble up to this parent object and then jQuery will have to go through every one of the delegated events for this particular event and it will have to evaluate the secondary selector argument to see if it matches the target object. If you have a lot of these delegated event handlers on the same object and you the secondary selector is somewhat complicated, it's possible that the time to process all this could start to be noticeable.
As with any performance issue, if this is really important to you, then you need to do your own performance testing. Install 30 delegated 'click' handlers with secondary selectors like you will be using to the document
object in a sample page and try it. See if you can see any performance degradation at all between the click and the response to the click. Try it with 100 event handlers, 1000 event handlers, etc... until you see where it becomes noticeable.