简体   繁体   中英

Performance penalty for jQuery's live() function

For certain elements, whenever hovering over them I want the elements to get larger and then shrink back down when unhovering. So I simply use $('.elementClass').hover(function() { enlarge(this); }, function() { shrink(this); }); . I put this in the $(function() { }); area of all webpages as many webpages have these kinds of elements.

Sometimes I need to create new dynamic elements and they have these elements above. Of course, I have to call the above hover function again for them because they didn't exist at first.

What seems to be most convenient is to simply have a whole battery of $('.variousClasses').live('variousEvents', function() { }); calls in every webpage for all possible functionality like the above.

So the question is if there's a performance penalty for calling live() so many times even on elements that won't ever fire those events or elements which will never exist? Is it important that I be careful about only calling hover() or live('hover') (and other events) only when needed?

As a general answer to your question, you should attempt to minimize extraneous function calls--maybe more so in a dynamic content situation.

In particular, live() is a good example to use for this question because it does carry with it some (potentially) significant performance complications. When you call live() , jQuery binds the event you have selected to the document object. This means that every time the event is fired, it bubbles up from the origin element to the document object. Depending on your site structure (and just in general), this can be costly.

A much better alternative with delegate()

It's better to use jQuery's delegate() function, especially if you have a pre-defined parent container element that all of your events will be firing within. When you use delegate() , you're basically using a restricted version of live() such that the event only propagates to the specified parent element. As a result, you avoid many potentially costly event fires on elements you do not care about.

In your case, since you are working with dynamically generated content, you either have to use the aforementioned functions or setup your code such that when the element is inserted into the DOM, it also binds the event handler to it. The former is likely easier, but the latter could offer marginally (likely indiscernible) better performance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM