I update a container with AJAX. Which one is better in terms of performance? Pseudo-code:
$.post('get_something.php',function(data){
$('#container').html(data).find('a').bind('click',function(){
console.log('Doh!');
});
});
Or this?
$('#container a').live('click',function(){
console.log('Doh!');
});
$.post('get_something.php',function(data){
$('#container').html(data);
});
Firstly, I wouldn’t recommend using
liveat all (and the jQuery team have deprecated it). I’d usedelegate(or the new version ofon) with a more targeted container (in your case,#container) than the document as a whole.If you do that, performance at click-time will be so close to the same as to make no difference (we’re dealing with a user-generated event here, the odd extra couple of milliseconds makes no never mind).
There are other considerations to (um) consider, though. Suppose we have this markup:
…and this code:
Since the
ais the deepest element, you’d expect a click on theato be handled by the first handler and to see theconsole.logentry. But you won’t, because the click isn’t actually handled until it reaches the container — and in this case, it won’t reach the container because the wrapper element in-between them stops the event.It’s not a negative (I find
delegatehugely useful and use it all the time), it’s just something to consider when you’re designing how you handle things.