Script47 Script47 -4 years ago 106
HTML Question

Forcing garbage collection in JavaScript class

I posted this question and what I can gather from the responses is that I need to force the garbage collector to remove code which has been removed from the DOM but where references still exist in memory. I've looked around and I can't seem to find a proper solution, in 2017, is there a viable way to collect the garbage?


function class_blah() {
this.var_blah = 'blah';

this.func_blah = function () {};

var blah = new class_blah();

/** Stuff happens here... **/

Then say I remove that dynamically loaded script and load some more content in to the DOM, how I can get garbage collector to now remove that?

The linked question should give you a better idea in regards to the issue I'm facing.

Answer Source

var blah = "something"; in the global scope attaches blah to the window object:

var blah = "something";


that means that when the script is removed, the reference to blah will still exist because window still exists.

One way to get rid of all of the references (stored in variable) is to not use global variables in the yet-to-be-removed scripts. Wrapping their code in an IIFE (Immediatel Invoked Function Expression) could do:

(function() {
  var blah = "something";     // only visible within this function

console.log(window.blah);     // no reference to blah is attached to window, so when the script is removed, blah will be destroyed

Unfortunetly, if the yet-to-be-removed scripts explicitly attach references to persistent object such as window or document, wrapping them in IIFE won't solve the problem.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download