J0HN
J0HN

Reputation: 26941

Remove all handlers from all elements

There's a bunch of questions about how to remove all "specific" handlers (e.g. onclick) from elements, or purge all events from an element, etc.

  1. How to remove all Click event handlers in Jquery
  2. Jquery: how to release all event handlers, dom changes?

This question is a bit broader. We were facing huge memory leaks in the asp.net site under IE7 and IE8, and one of the tweaks to shrink those leaks was to unbind all events from all elements on the page. Basically this:

$('*').off();

Now, we're trying to improve the performance of the application and, to no surprise, this particular line is one of the hot spots.

So, the question is: are there any way to achieve the same result (explicitly removing all the handlers from all the elements in the document) more efficiently?

No-go options:

What I was thinking of is to use some jQuery internals (maybe even non-public API) to leverage the detection of element with handlers attached. But it's slightly above my current competency with jQuery. If it helps, we're targeting jQuery 1.7.1.

Upvotes: 2

Views: 288

Answers (1)

Donald Byrd
Donald Byrd

Reputation: 7778

I suppose you could create something like hasEvent to detect events but I suspect your issue is more traversing the dom than calling .off() on elements that have no events. You could test it to make sure.

Depending on the nature of your application you might gain some performance by tweaking your selector to target your elements more precisely.
See: http://www.artzstudio.com/2009/04/jquery-performance-rules/

Another idea would be to override jQuery functions that add your event handlers so you can populate your array for later use. It wouldn't require modifying your hundreds of files but would still give you more direct access for later manipulation.

Upvotes: 1

Related Questions