Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery performance: $('#selector').live() vs manually bind (when working with ajax requests)

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(); });  
    }
});

?

like image 884
nemesisdesign Avatar asked Nov 12 '10 11:11

nemesisdesign


1 Answers

There are different costs, let's look at them:

$('#mybutton').live('click', function(e){ doSomething(); });

There are 2 main costs here:

  • The #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]).
  • Every 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:

  • The #mybutton selector runs, but only once per ajax request. However, we're not wasting it, we're using the results.
  • The click handler is bound to an actual element, rather than document, so there's a binding cost each time it runs, rather than once

However, 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.

like image 72
Nick Craver Avatar answered Sep 30 '22 16:09

Nick Craver