开发者

.live() or document.ready?

开发者 https://www.devze.com 2023-03-18 04:31 出处:网络
Which one is better for performance when attaching events (click, mouseover, mouseout, etc...)?I am attaching a lot of event listeners to my elemen开发者_StackOverflow中文版ts in liu of :hover events

Which one is better for performance when attaching events (click, mouseover, mouseout, etc...)? I am attaching a lot of event listeners to my elemen开发者_StackOverflow中文版ts in liu of :hover events and am wondering if there is a performance difference between the two.


You're thinking of it in the wrong way. live() is a very expensive observer, avoid it if you can and use delegate() instead. If you are not using ajax or javascript to create DOM nodes after DOMready, then you don't have to worry about attaching an observer to the event:

$(function(){
    $('#my_node').click(function(){}); // will work fine for all nodes loaded before domready
});


It depends on your needs, But here's a general rule:

Try to bind with .bind() whenever it's possible, Bind with .live() as less as you can

(Note that bind('event', ...) has aliases, like '.click()')

So, prefer binding in document.ready() than using .live() because live consumes much more resources, as is always 'listening' for changes.

Hope this helps. Cheers


$(document).ready(function() {
    //Put all your events here, where they'll be live anyway
});
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号