“JScript - script block” and memory leaks - How to freeing up resources properly?

佐手、 提交于 2019-12-04 03:11:49

Script that's parsed by a browser is not in the DOM, and you can't "remove" it - variables are still defined, events are still bound, methods are still there. If you put javascript into a partial view that you load repeatedly, you're going to get that javascript repeatedly.

What you need to do is author your javascript to be more resilient to this. If you're binding events to elements outside of the dynamic area - don't. You'll be binding them multiple times. Move that code somewhere it will only be loaded once. Try to keep the javascript in the dynamic area isolated so it only deals with elements that are also in the dynamic area.

You can also protect against multiple definitions with simple if checks, using jquery selectors that more scoped, etc.

Without the details of what's in that repeated block, there's not much I can offer.

It seems to me like your problem is that every time you load a tab, all the scripts in it get loaded too, and as far as I'm concerned, there's nothing you can do about it, remember that you can use server-side code to generate those scripts so ASP.NET has to act like they are all different (since they can actually be).

However, javascript IS garbage collected so I don't think those scripts you see are actually taking up user's memory when your not debugging, the debugger will always show everything that was loaded regardless of it having been garbage collected or not (although I didn't actually test it).

If your worried about memory, just make sure you're not declaring global functions and variables that'll never be garbage collected (specially in scopes that get reloaded), to do this, just surround them with a

(function(){

and a

})();

So that they're in an anonymous function that can be garbage collected right after it's executed.

You just need to collect all scripts within the tabs, in the document ready event. The code below find all script children of an element, execute them and then destroy them, so they cannot be executed again:

function GlobalEvalScriptAndDestroy(element) {
var allScriptText = CollectScriptAndDestroy(element);
jQuery.globalEval(allScriptText);}



function CollectScriptAndDestroy(element) {
var allScriptText = "";
if (element.tagName == "SCRIPT") {
    allScriptText = element.text;
    $(element).remove();
}
else {
    var scripts = $(element).find("script");
    for (var i = 0; i < scripts.length; i++) {
        allScriptText += scripts[i].text;
    }
    scripts.remove();
}
return allScriptText;}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!