问题
I've written a fairly large web app. It works good for awhile and then slowly starts running sluggish as DOM nodes start creeping around 80,000 - 100,000.
So I've been screweing around with some small data sets in the Chrome Dev Tools console (DCTC).
Can someone tell me why the following works sometimes and then sometimes it does not.
var test = $('<div></div>');
test.remove();
test = null; //Doesn't seem to make a difference when it doesn't work
If I watch the DOM node count under Timeline in CDT, the sometimes the node count will be correct, other times it seems to refuse to give up the DOM node I'm trying to remove. This is even after pushing the GC button.
The following seems to be consistent in removing the DOM nodes and freeing memory.
//Seems to remove nodes just fine
for(var i = 0; i<100; i++){
var test = $('<div></div>');
$("body").append(test);
}
$("body").empty();
In regards to the first example, I thought that perhaps it didn't work sometimes because of the NODELETE flag because it's a variable definition, so I tried putting my assignment on an object but that did not help. It actually seems to be more consistent that jQuery's remove would not remove the dom node.
//Does not remove the node.
var test = {};
test.node = $('<div></div>');
test.node.remove();
test.node = null;
Why the inconsistency?
Observation:
if I do test = document.createElement('div');
it will consistently create a detached node. var test = ....
seems to be consistent in allowing me to clear the node until it messes up and then all bets are off.
In response to everyone saying there is no DOM node, please read this: https://developers.google.com/chrome-developer-tools/docs/heap-profiling-dom-leaks The DOM nodes I'm trying to delete show up here in the detached dom nodes, but "how do I get rid of them" is the looming question still.
回答1:
After some more testing, here is what I came up with:
The console does correctly show the DOM node counts. It also however seems to handle variable declaration and removing DOM nodes incorrectly. If I run my examples from script, they work just fine, not from the console though.
If I do:
<script>
var test = document.createElement('div');
test = null;
var test = {};
test.node = document.createElement('div');
delete test.node;
var test = $('<div><div></div><div></div></div>');
test.on("click", function(){
alert('yes');
});
test.remove();
test = null;
//test = null;
var test2 = {};
test2.node = $('<div></div>');
test2.node.remove();
delete test2.node;
</script>
From inside my page, it correctly frees up the memory and orphaned DOM nodes. If I do not set the variable to NULL or delete it from an object, the detached DOM node will remain there and there is no way to remove it as you don't have a reference to it anymore.
I think this is a good word of caution to those using jQuery and relying on the remove() function solely.
来源:https://stackoverflow.com/questions/21240709/javascript-freeing-the-dom