Avoid memory leaks with jQuery / .data ()

I am using jQuery to dynamically create HTML elements, and now you need to store JavaScript data against them. However, now I'm worried about a memory leak, as I never call delete my objects. I have '.append' and '.detach' them, but never '.remove'. The documentation for jQuery seems to suggest that I have to call deletion to clear it of the object - events, data, etc.

Is it strictly necessary for modern browsers, or does the disappearance of any link to an element do this for me?

Another way to talk about my question; Does this memory leak script?

function createElement() { var newDiv = $("<div>") .data("test", "test data") .appendTo(document.body) .detach(); setTimeout(createElement, 10); } createElement(); 

In this case, this memory leak even without calling .data ()?

I am not interested in supporting very old browsers. IE9 and better, basically.

+6
source share
1 answer

From http://api.jquery.com/jQuery.data/ : "The jQuery.data () method allows us to bind any type of data to DOM elements in such a way that it is safe from circular references and, therefore, from memory leaks. We can retrieve several different values ​​for a single item, one at a time or as a set. "

Also, remember that you can use HTML5 data attributes to store data.

+2
source

Source: https://habr.com/ru/post/958174/


All Articles