Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is inline javascript garbage collected when document body is replaced?

Consider I have the below webpage written in HTML (body section only):

<body>
    <p>
        ...
    </p>

    <script>
        function fn() {
            // do stuff
        }
    </script>
</body>

Now, if I replace the innerHTML of document.body from JavaScript with say, a div, so that the body part becomes:

<body>
    <div>
        ...
    </div>
</body>

... then is the fn object eligible for garbage collection if no references to it exist anywhere in the rest of the code (any context)?

like image 367
John Weisz Avatar asked Jul 23 '15 16:07

John Weisz


People also ask

Does JavaScript do garbage collection?

Some high-level languages, such as JavaScript, utilize a form of automatic memory management known as garbage collection (GC).

How could you make sure a const value is garbage collected?

WARNING Assigning an object or array as a constant means that value will not be able to be garbage collected until that constant's lexical scope goes away, as the reference to the value can never be unset. That may be desirable, but be careful if it's not your intent!


2 Answers

It would be subject to garbage collection if no other references were made to it from any context. However, there is one small reference that is holding on to that function, the global window object. This is because the function (and entire script section shown) is scoped globally. This reference will still exist even if the entire document.body's innerHTML is replaced.

There are only a few ways to free the object shown in your exact example from the global object and make it eligible for collection. Deleting the property on the global object is not an option because it was declared as a function and not as a property.

  • Overwrite the property on the global object with something else. window.fn = [][0]; (undefined shortcut)
  • Navigate away from the page so that the global object becomes eligible for garbage collection.

Quick note on garbage collection, it occurs when the browser feels that it is necessary, and not immediately after an object has no references (or at least, not usually - this may happen from time to time).

like image 119
Travis J Avatar answered Oct 24 '22 05:10

Travis J


Just tested this out, and interestingly, no.

http://jsfiddle.net/wah754La/1/

Test code:

body:

<script type="text/javascript">
    function foo () {
        // i exist!
    }
</script>

and on load, this is run:

document.body.innerHTML = '';
console.log(foo);
// logs 'function foo()'
like image 42
deleted user Avatar answered Oct 24 '22 05:10

deleted user