When working with content loaded asynchronously is there any difference from a performance point of view between:
// .live()
$('#mybutton').live('click', function(e){ doSomething(); });
and manually bind() the events we need every time after the content has been loaded:
// manual bind every time
$.ajax({
url: url,
success: function(data){
mycontainer.html(data); // data contains #mybutton
$('#mybutton').click(function(e){ doSomething(); });
}
});
?
There are different costs, let's look at them:
$('#mybutton').live('click', function(e){ doSomething(); });
There are 2 main costs here:
#mybutton
selector needs to run immediately for no reason (the result is thrown away, we just wanted the selector anyway...we're binding to document
). In this case it's an #id
selector so that's a very low cost...in other cases it's not cheap and very wasteful (for example [attr=something]
).click
that bubbles up to document
now has to be checked against this selector, a per-click evaluation cost, this varies with the number of clicks you expect.Now let's look at the other method:
$('#mybutton').click(function(e){ doSomething(); });
There are 2 main costs here as well:
#mybutton
selector runs, but only once per ajax request. However, we're not wasting it, we're using the results.click
handler is bound to an actual element, rather than document
, so there's a binding cost each time it runs, rather than onceHowever, there's no per-click cost and the selector call itself isn't wasted...so it's better overall, since you're using an ID, this isn't true in other cases.
In your case, since you're dealing with an ID (and guaranteed a single element), this is much cheaper:
$('#mybutton').click(function(e){ doSomething(); });
In other cases, where you're binding hundreds of elements, .live()
is the clear winner, though .delegate()
would be even better.
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