atul atul - 4 months ago 13
Javascript Question

Will adding and removing a DOM element dynamically create memory leaks?

I am adding a div to the DOM and the performing some animation on it. Once the animation is over, I am removing the div from the DOM again, like this:

$div = $("<div />", {id:"flashMsg", class: className, html:msg}).prependTo(bazingaApp.app.rightPanel);

$div.fadeIn("slow",function(){
$(this).delay(5000).slideUp(1000, function () {
$(this).remove();
});
});


Will this create any memory leak?

Answer

It won't if $div is a variable that goes out of scope. It will if the $div variable is kept in memory. If there's only ever a single $div variable, it'll be a really really tiny leak. If $div is created and kept repeatedly (e.g., in a function where it's captured by a closure), that tiny leak will add up. Most likely, it's fine, but we'd need more context to be able to say for sure.

To avoid that possibility, you can get rid of the variable entirely:

$("<div />", {
    id:"flashMsg",
    class: className,
    html:msg
})
.prependTo(bazingaApp.app.rightPanel)
.fadeIn("slow",function(){
   $(this).delay(5000).slideUp(1000, function () {
       $(this).remove();                    
   });
});