Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is necessary to call empty() before html() or before innerHTML?

I have a popup plugin which sets the html content of a <div/> with the response of an AJAX call.

Every time i open the popup, in the code i just call $("#popup").html(response). This overrides the existing html content with the new content.

Should i call $("popup").empty() before i call $("popup").html(response) so i release the browser memory used by the objects which were previously in the $("popup") div? (eventually prevent memory leaks)

PS: what if i call $("popup")[0].innerHTML = response ? should i call .empty() method?

like image 894
Catalin Avatar asked Jun 03 '13 12:06

Catalin


2 Answers

No need to call empty().html(response) method ovverides the existing content.

like image 88
Suresh Atta Avatar answered Sep 20 '22 01:09

Suresh Atta


Short answer no.

jQuery.fn.html uses DOMNode.innerHTML = after doing several other things. One is to remove any stored data on nodes (stored via $.fn.data), see http://james.padolsey.com/jquery/#v=git&fn=jQuery.fn.html for full source overview.

.innerHTML removes the children and replaces with the new html. But beware of memory leaks. I would use jQuery.fn.empty before setting innerHTML. eg.

var a = document.createElement('div'),
    b = document.createElement('div');

    b.appendChild(a);

    b.innerHTML = 'new innerHMTL'.

You would think everything is ok. But the node replaces/removed is still captured in the varible a and therefore isn't thrown to the garbage collector. I'm not sure wether or not that jQuery stores DOMNodes internal until you call jQuery.removeData etc.

like image 22
Andreas Louv Avatar answered Sep 20 '22 01:09

Andreas Louv