views:

85

answers:

2

Recently I have to execute script retrieved thru Ajax from web server periodically. I do it by first creating a Script tag and assign the text attribute to run the script. Then, I dispose the script tag just to find out that memory keep increasing on every creation in IE 7. The following HTML illustrate the problem:

<html>
<body>
<span id='m_garbageBin'></span>
<script type="text/javascript">
    function buttonClicked()
    {
        for (var i = 0; i < 100000; i++)
        {
            var sc = document.createElement("script");
            sc.text = "var x=1;";
            document.body.appendChild(sc);
            m_garbageBin.appendChild(sc);
            m_garbageBin.innerHTML = '';
        }
    }
</script>
<script id='m_dynamicScript' type="text/javascript">
</script>
    <input type='button' value='Click me!' onclick='buttonClicked();'/>
</body>

The script isn't doing anything at all and still memory keep increasing on every click on the button in IE but not in Firefox (by using .innerHTML instead of .text). The fact that I have to retrieve the script to execute periodically cannot be changed. Anybody knows what I can do to avoid the memory increase in IE?

A: 

try delete sc; when after setting the innerHTML to ''.

prodigitalson
Thanks for you suggestion but it didn't do the trick.
Conrad
The `delete` statement will actually fail (it will return false, and nothing will be deleted), because the variable instantiation made in the *"Function Code"* execution context, sets the variables with the `{ DontDelete }` property attribute, more info: http://bclary.com/2004/11/07/#a-10.2.3
CMS
+4  A: 

Try to remove the script elements just after they are appended, something like this may help:

function buttonClicked() {
    var head = document.getElementsByTagName('head')[0];
    for (var i = 0; i < 100000; i++) {
        var script = document.createElement("script");
        script.type = "text/javascript";
        script.text = "var x=1;";
        head.appendChild(script);
        head.removeChild(script);
    }
}

That's the way some modern libraries, like jQuery make it.

See also:

CMS
As far as I know, IE has problem regarding the removeChild function that it doesn't actually release the memory until the page is unloaded even an element is removed using that call. Some refer that as "psuedo-leak": http://www.mail-archive.com/[email protected]/msg05231.html
Conrad