Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens to unused DOM elements?

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?

like image 834
TheSHEEEP Avatar asked May 25 '12 10:05

TheSHEEEP


People also ask

What is a detached DOM element?

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.

What is special about DOM element?

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.

How do I get all the elements in the DOM?

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.

How many DOM elements are there?

There are over 1,500 DOM nodes in total. There are more than 1500 HTML elements on your web page.


1 Answers

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 nulling 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.

like image 187
jAndy Avatar answered Sep 23 '22 14:09

jAndy