admin管理员组

文章数量:1289515

var domElementReference = $(document.createElement('div'));

Will the DOM element get destroyed if I don't actually insert it on the page (once domElementReference gets out of scope)?

If not: If I have a constructor-function that creates DOM elements, is there an automatic way to clear them in javascript?

What I tought was to append them on an element, and then use

myChildNode.parentNode.removeChild(myChildNode);

But than again I have to manually call the function when the object is getting out of scope, and it kind of messes up the whole 'garbage-collection' idea. Any patterns to automatically destroy the object?

var domElementReference = $(document.createElement('div'));

Will the DOM element get destroyed if I don't actually insert it on the page (once domElementReference gets out of scope)?

If not: If I have a constructor-function that creates DOM elements, is there an automatic way to clear them in javascript?

What I tought was to append them on an element, and then use

myChildNode.parentNode.removeChild(myChildNode);

But than again I have to manually call the function when the object is getting out of scope, and it kind of messes up the whole 'garbage-collection' idea. Any patterns to automatically destroy the object?

Share Improve this question edited Apr 14, 2014 at 10:17 asked Apr 14, 2014 at 10:04 user1546328user1546328
Add a ment  | 

1 Answer 1

Reset to default 12

If the elements haven't been inserted into the DOM and no other references exist, then yes they will be garbage collected, just like any other variables.

Modern browsers use a Mark-and-sweep algorithm for garbage collection, this means the garbage collector will look for and garbage collect objects that are unreachable. If you create elements in your function, but don't assign a reference elsewhere or don't insert them into the DOM, then they will be eligible for garbage collection after the function pletes.

There is no need to manually try to free memory in JavaScript, it is all handled implicitly.

  • MDN documentation for Memory Management in JavaScript.

本文标签: Do DOM objects get garbage collected in javascriptStack Overflow