Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Javascript remove event handlers of deleted DOM elements?

Tags:

If I attached a bunch of events to some DOM elements - and then remove them - will the memory used for their event handlers or other attributes still be used?

I ask because I want to know if I will use a bunch of memory if I keep refilling an area of a page with new elements from AJAX requests and binding events to them - only to delete them and repeat the process when a new AJAX result comes in.

like image 418
Xeoncross Avatar asked Dec 17 '11 19:12

Xeoncross


People also ask

Is event listener removed when element is removed?

According to the jquery Documentation when using remove() method over an element, all event listeners are removed from memory. This affects the element it selft and all child nodes. If you want to keep the event listners in memory you should use . detach() instead.

Can event handlers be removed?

Go to the objects tab, view the Document object (don't click on edit) and scroll down to Event Handlers. Select the one to delete and press delete.

Does DOM use event handlers?

DOM elements can have functions hook onto events. The functions are called event handlers and the DOM element is known as an event target. The example code block shows how to register a function as an event handler.

Do I need to remove event listeners in JS?

TLDR; Always remove event listeners when you don't plan on using them any longer.


1 Answers

Yes, modern browsers (eventually) release the memory used by event handlers in DOM nodes. However, old versions of Internet Explorer don't, so it's always good practice to remove event listeners before removing the nodes from the DOM.

This is a good article for understanding what's going on: http://msdn.microsoft.com/en-us/library/bb250448(v=vs.85).aspx

like image 180
juandopazo Avatar answered Oct 26 '22 21:10

juandopazo