Avoiding memory leaks with jQuery / .data()

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.

Answers


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.


Need Your Help

Why is PHP converting '+' to a space even when escaping URL with %2B?

php mod-rewrite escaping

I can't seem to pass a '+' symbol to a php file (index.php), even though I'm escaping it properly. To debug the problem I set up a test file (test.php).

Used git checkout to revert a file - anyway to restore it?

ruby-on-rails git checkout restore revert

I'm picking up work on this Rails system, and was told I could modify the server to do some testing. I made a small change to a few files for testing, confirmed my suspicions, and then did a recurs...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.