Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why object has to be nulled for IE after it was document.getElementById-ed?

I often see in third party JavaScript code that after:

var el = document.getElementById(elementId);

object is often nulled and comment along this operation says that it is done for IE:

el = null; // IE

What's the real purpose? Any resource on that?

like image 885
jayarjo Avatar asked Jul 11 '11 06:07

jayarjo


1 Answers

By nixing a reference they break the corresponding cyclic dependency between the DOM object and JavaScript objects, which are controlled by different sub-systems in older IE (thus being impossible to be garbage-collected).

For example:

var el = document.getElementById(elementId);
el.onclick = function () { // here the cyclic reference is created
    /...
};

The JavaScript subsystem has now a reference to the el element, and the DOM subsystem (the el element) has a reference to the JavaScript object (the function plus what it closes in).

You don't have to worry, though, if you add the listeners via addEventListener.

To read more about common memory leak pitfalls, see http://www.ibm.com/developerworks/web/library/wa-memleak/.

like image 72
katspaugh Avatar answered Nov 15 '22 03:11

katspaugh