6

I'm using jQuery to dynamically create HTML elements, and now have a need to store JavaScript data against them. However, I'm now concerned about memory leaks as I never actually call 'remove' on my objects. I '.append' and '.detach' them, but never '.remove'. The documentation for jQuery seems to suggest that I should be calling remove to clean up it's footprint on the object - events, data, etc.

Is this strictly necessary on modern browsers, or will the disappearance of any reference to the element do this for me?

Another way to phrase my question; does this script snippet leak memory?

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

    setTimeout(createElement, 10);
}

createElement();

For that matter, does this leak memory even without the .data() call?

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

Blazemonger
  • 90,923
  • 26
  • 142
  • 180
Barguast
  • 5,926
  • 9
  • 43
  • 73
  • You can use your browser's developer tools to monitor memory used by the page. In Chrome, it's under "Timeline". – Blazemonger Nov 15 '13 at 21:20
  • 4
    jQuery creates an object that it calls $.cache internally, this is where all the data you attach with .data() is stored, the element itself only gets one single new property containing an ID that is used as the key for the $.cache object to retrieve the data. So, jQuery's remove() will erase any data stored in $.cache, and it will remove any event handlers, and does its best to clean up all the mess you've made. detach() obviously doesn't do this, as that is the point, to keep all data associated with the element. Normally you shouldn't have to worry about this at all as it's not that many kb – adeneo Nov 15 '13 at 21:31
  • As a sidenote, data() works this way to ensure it doesn't leak memory or cause issues with circular references, and no, the data doesn't just disappear in modern browsers (nor old browsers) as it's stored internally by jQuery in a special object. – adeneo Nov 15 '13 at 21:36

1 Answers1

2

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

Also, don't forget that you can use the HTML5 data-* attributes to store data.

Adrian
  • 222
  • 2
  • 11
  • Thanks. It seems the way I want to do this will leak, but I can work around using data(). Do you know if calling detach() rather than remove() will cause any other memory issues? – Barguast Nov 16 '13 at 12:45
  • 1
    The .detach() method is the same as .remove(), except that .detach() keeps all jQuery data associated with the removed elements. This method is useful when removed elements are to be reinserted into the DOM at a later time. – Adrian Nov 20 '13 at 05:47