Let's say I create a class that has its own canvas with:
this.canvas = document.createElement("canvas");
I use that canvas, draw some stuff, etc., but never add the canvas to the DOM tree. And when I'm done, I won't use the whole class any more.
So when I delete the class that used the canvas, does the canvas still take up memory? Do I have to delete it in some way?
Or, as a more general question: What happens to unused elements that are not in the DOM tree any more or never were (not visible in the website)? Will they be garbage collected and/or can you speed that up a bit to increase performance?
A memory leak can occur in your application when an element is no longer attached to the Document Object Model (DOM) tree, but is still referenced by some JavaScript running on the page. These elements are called detached elements.
The Document Object Model (DOM) is a programming interface for web documents. It represents the page so that programs can change the document structure, style, and content. The DOM represents the document as nodes and objects; that way, programming languages can interact with the page.
To get all DOM elements by an attribute, use the querySelectorAll method, e.g. document. querySelectorAll('[class="box"]') . The querySelectorAll method returns a NodeList containing the elements that match the specified selector.
There are over 1,500 DOM nodes in total. There are more than 1500 HTML elements on your web page.
As you already correctly noted yourself, this is not about the DOM tree, its more about object referencing & garbage collectors.
When you delete/remove a class by null
ing the base object, all modern collectors will take care of you. By not even inserting the node into the DOM you don't have to fear any hidden references aswell. I've seen several people explicitly setting the <canvas>
reference to null
also, but I guess this is pure IE8 paranoia.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With