Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p><em>rewritten to clarify further</em></p> <p>There's actually 2 causes for memory leaks in the offered example. The first memory leak manifests due to creating a <strong>direct</strong> reference to a live DOM node inside a closure. The garbage collectors (JS &amp; DOM) of legacy browsers such as IE6 cannot nullify such references. Hence the need to null out node references at the end of your function.</p> <p>jQuery circumvents this by default due to live DOM elements being attached to the jQuery object as attributes/properties, with which the afore mentioned garbage collectors have no trouble in determining null references. If the jQuery object has null references it's simply cleaned up and it's attributes/properties (in this case references to live DOM elements) along with it.</p> <p>So in order to avoid this memory leak, is to have an object maintain the reference to the live DOM node and then reference to the object in your closures. The closures will only maintain the references to the object and not the live DOM element since that reference belongs to the object.</p> <pre><code>// will still leak, but not due to closure references, thats solved. function noLeak(){ var obj= { elem: document.createElement('div') } obj.elem.onclick = function(){ obj.elem.innerHTML = obj.elem.innerHTML + "."; } } </code></pre> <p>This cleared the most obvious circular reference, but there's still a leak (onclick). The node has a reference to a function which has a reference to the object which in turn has a reference to the node. The only way to circumvent this leak, is to learn from the <a href="http://www.quirksmode.org/blog/archives/2005/09/addevent_recodi.html" rel="nofollow noreferrer">addEvent</a> contest (lots of people worked to solve this leak ;) ). Coincidentaly, needed code can be found therein so my appologies for not supplying code for that ;)</p> <p>Creating a wrapper for the event system adds some more code, but is essential. The main idea is to add a common eventHandler that delegates the event to an event cache/system which stores the required references. On an unload event, the cache gets cleared breaking circular references allowing the garbage collectors (JS and DOM) to tidy up their own corners.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload