My team is building a mobile website using jQuery Mobile, and as we are nearing the release date performance is becoming more of a concern. One observation I've made is that we have lots of calls to live()
and delegate()
throughout our code; but in fact, to my knowledge, we are only ever using these methods to attach event handlers to DOM nodes that already exist (and will always exist, in the context of our application).
Given that live()
and delegate()
are both intended to provide dynamic binding to nodes that may appear later on in the DOM, and considering that each of these involves handling events that have bubbled all the way up to the document
root node, I wonder if we would see a performance improvement by changing these calls (where appropriate) to bind()
instead.
I'm aware that I could probably test this in some way myself, but I don't have a great deal of experience doing performance testing with JavaScript and I'm thinking it would probably take me longer to figure out than it would for me to simply ask the community. Has anyone tested this? Is there a measurable difference? Or would switching these live()
and delegate()
calls over to bind()
be a waste of time?
The bind() method will not attach events to those elements which are added after DOM is loaded while live() and delegate() methods attach events to the future elements also. The difference between live() and delegate() methods is live() function will not work in chaining.
on() method is the preferred method for attaching event handlers to a document. For earlier versions, the . bind() method is used for attaching an event handler directly to elements. Handlers are attached to the currently selected elements in the jQuery object, so those elements must exist at the point the call to .
bind() has been deprecated. It was superseded by the . on() method for attaching event handlers to a document since jQuery 1.7, so its use was already discouraged.
It depends on how you use it but delegate offers the best performance (not necessarily in terms of speed only but overall) in most cases:
http://www.alfajango.com/blog/the-difference-between-jquerys-bind-live-and-delegate/
I haven't measured anything, but live
is likely to be faster than bind
for larger numbers of elements, since bind
needs to affect every element.
If you bind
an event to 200 elements, jQuery needs to loop through all of those elements and call addEventListener
on each one.
If you live
an event to 200 elements, jQuery just adds a single event handler to the <body>
.
However, this means that every event that bubbles up to the body must be tested against each selector that you have live
d.
Therefore, the fastest option should be to delegate
to the element that contains as little as possible (so that it gets fewer other events that must be tested against your selector)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With