开发者

IE leaks memory for dynamically generated javascript

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'>&l开发者_如何学编程t;/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?


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:

  • Global Scope Evaluation and DOM Investigation


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜