Skip to content Skip to sidebar Skip to footer

Is It Bad To Bind Behaviours To Document Unconditionally?

The pagination controls on a page I am working on were being bound conditionally on there being more than 1 page. I don't like to see the following code in my projects, if (pages &

Solution 1:

Yes, this is causing significant unnecessary overhead, and it is a "bad practice".

Binding your event handling to the top-level document object means that every single click that occurs on any element anywhere in your page will bubble up to the document object, where the event's target is checked to see if it matches .pagination .next.

In fact, the documentation itself recommends against your usage:

Attaching many delegated event handlers near the top of the document tree 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.

So, you're misusing on. It's for binding directly to elements or to parent elements which may have dynamically created children, and you are meant to bind to the closest possible parent element. Binding to the document is certainly not meant to be the only way you handle events in your page.


Post a Comment for "Is It Bad To Bind Behaviours To Document Unconditionally?"