Dom versus JS engine - Circular references
What is part of JS engine? var a=1; var arr = new Array(); var myDiv1 = [ now DOM... ] document.getElementById('DivA') var myDiv2 = [ now DOM... ] document.createElement('DIV')
What is part of DOM engine? A table in your HTML document with id='myTable' A span in your HTML document with id='mySpan' document.getElementById('DivA') var x = [until here JS engine] new XHTMLRequest(); // used in Ajax....
What is an expando? (expando property)
Expanding a HTML Element with an event handler OR expanding by a "self made" variable that you may attach to a standard HTML Element. Expanding by an event handler:
document.getElementById('DivA').onClick = alert(); document.getElementById('DivA').onClick = new function(...); document.getElementById('DivA').attachEvent = dosomething;
Expanding by a "self made" variable:
document.getElementById('DivA').myData = "Some text";
The following is NOT an expando: (you just have a simple reference from JS [x] to Dom [getElementById(), but thats not the subject here]
var d = document.getElementById('DivA'); d.style.color="red"; d.id= "divNumber12";
The following IS an expando:
d.MySelfDefinedId = "divNumber12"
Because MySelfDefinedId is not part of the standard attributes of a div. It is an attached variable that creates the reference back to JS engine. Now the problems show up, when you have more then one reference between DOM an JS (circular references)
Example: d.MyId = "divNumber12" where d means actually: document.getElementById('DivA')
So we have JS > DOM > JS engine [JS in bold]
d = document.getElementById('DivA') . MySelfDefinedId = "divNumber12";
The same if you attach an event to the DIV;
d = document.getElementById('DivA') . onclick = dosomething();
How to resove this? It is very simple....
Just assign null to the expando (EventHandler or "self made" variable) when unloading the page or destroying the object.
Example: d.onclick= dosomething();
That means actually:
Now assign null and the circular reference has gone. You will not have anymore 2 references to the DOM part.
d.onclick=null; or d.MyId= null;
If you have any circular references, you must remove them using the body onunload event by calling a cleanup function.
function cleanupOnUnload(){ Remove any circular reference (Event handler etc) }
THERE IS NO NEEDE TO USE THINGS LIKE:
d.onclick= new function(){} or delete d.onclick or whatever strange solutions you will find on the web.
I DO NOT RECOMMEND USING EXPANDO VARIABLES TO BE ATTTACHED TO DOM ELEMENTS Accessing expando variables is much slower than storing the data in an Array and then reference the object by the array itself.