3

I have a very dynamic web application, elements are created and destroyed constantly.

In order to make clicks and other events stay, I'm attaching all of these events to $(document), like this example:

 $(document).on('click', '.tabs li a', function(event) {

 });

Like I said, almost all of these events are being attached to $(document).. are there any drawbacks to that? Where are these event handlers stored? Will it make my application slower?

sigmaxf
  • 7,998
  • 15
  • 65
  • 125

2 Answers2

1

No - this negatively impacts the performance of your jQuery. You should NOT bind all delegated event handlers to the document object. That is probably the worst performance scenario you could create. As mentioned in the Event Performance section here in the jQuery documentation-

Attaching many delegated event handlers to the document can degrade performance. Each time the event occurs, jQuery must compare all selectors of all attached events of that type to every element in the path from the event target up to the top of the document. For best performance, attach delegated events at a document location as close as possible to the target elements.

Avoid excessive use of document or document.body for delegated events on large documents. For delegated event handling it is MUCH more efficient to bind them to the closest parent that is not dynamic.

An amazing detailed description of the problems can be found in this answer.

Hope this helps!

Community
  • 1
  • 1
Shekhar Chikara
  • 3,786
  • 2
  • 29
  • 52
0

tl;dr Binding listeners allocates memory. If you do this with a lot of listeners which are constantly being bind to the document, none of these listeners are ever turned off until the document is unloaded (i.e page refresh, hard loading another document as in old school html). Eventually in a SPA, you'll run into memory leaks and browser crashes

N R
  • 9
  • 2