I’ve found that all of these scripts, while doing the same thing create memory leaks, the question is, why?
It would seem it’s because of the circular references.
<script>
function runme() {
var node = document.createElement("div");
node.onclick = function() {
node.style.background = "red";
}
document.body.appendChild(node);
}
</script>
or
<script>
function runme() {
var node = document.createElement("div");
node.onclick = function() {}
document.body.appendChild(node);
}
</script>
or
<script>
var node = document.createElement("div");
document.body.appendChild(node);
function runme() {
node.onclick = function() {}
}
</script>
or
<script>
var node = document.createElement("div");
node.onclick = empty;
document.body.appendChild(node);
function empty() {
}
</script>
I don’t know how you detect the leaks, but for me only the first 2 examples create a leak.(detected using sIEve)
The reason: inside runme() you create a closure for node.
When you got leaks in all 4 examples, you should show, how you remove node(that’s the point when the leak occures )
However: the solution is to remove events before removing an element: http://www.crockford.com/javascript/memory/leak.html