开发者

can adding jQuery listeners slow down browser performance?

开发者 https://www.devze.com 2022-12-26 10:25 出处:网络
I have application that brings response via Ajax and creates 5-20 new jQuery click listeners on each refresh.Both IE and mozilla browsers seem to be slowing dow开发者_如何学JAVAn with usage.Can this s

I have application that brings response via Ajax and creates 5-20 new jQuery click listeners on each refresh. Both IE and mozilla browsers seem to be slowing dow开发者_如何学JAVAn with usage. Can this slow down browser performance significantly. Can listeners be "released"?


To add to what Andy said about live.

You should probably be using delegate or live on the elements you are adding to the page. It sounds like you are not binding unique events to the new elements (on each refresh) but rather reusing functions.

In jQuery 1.4.2 use can use delegate() like this:

// the container,        the selector, "the event", the function to be called
$("#container").delegate(".selector",  "click",     function(){
  // do stuff...
});

This would only need to be called once and every new element with the "selector" class added to the "#container" will have their click event bound


Listeners set using .bind() are released when the element is removed or .unbind()ed. Those set using .live() persist until you call .die() or the element they are bound to is removed (which may be somewhere in the DOM if you specify, otherwise it'll default to the DOM root - .live() works by not binding to the target element so the element can be removed/replaced/updated and the event listeners are still bound).

5-20 listeners sounds a few too many - consider binding less handlers if possible as older browsers will crack under the pressure far quicker than newer ones.


You can unbind a listener using unbind:

$("a").unbind("click"); // remove click event handler(s)
$("a").unbind(); // remove all event handlers

and remove live events using die:

$("#foo").die(); // remove all live events
$("a").die("click"); // remove live click event handlers
0

精彩评论

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