Unload external .js file

江枫思渺然 提交于 2019-11-30 18:54:45

问题


I'm loading some HTML and JS with AJAX:

main-page.html loads vía AJAX a page called page-to-load.html.

<!-- main-page.html -->
<html>
...
<script>
$.ajax({ 
  type:"POST", 
  url:"page-to-load.html", 
  success:function(data) { 
    $("#some_id").html(data);
  }
});
</script>
...
</html>

page-to-load.html includes html and a js file:

<!-- page-to-load.html --->
<script src="scripts-for-this-html.js"></script>
<p>This is a HTML page working with above external .js file</p>

As you can see, i'm loading a js file, scripts-for-this-html.js

This works perfectly. The problem is that if I loaded again (I mean, "#some_id" gets empty and loaded with page-to-load.html again) all the script (scripts-for-this-html.js) remains in the browsers memory (for example, if I have an event in this .js file, this event gets repeated as many times I had loaded the file, even if i have deleted the script element from the DOM).

Is there any way to get this work? I don't want to include all the .js files at once (ther are too many), I want to loaded and unloaded them by demand.


回答1:


JavaScript unloading could theoretically be done by removing the script tag (as you are doing with .html and by eliminating all references to any objects associated with the script. This involves deleting every reference and event listener. Even one left could keep that variable's functional scope in memory causing a leak.

It would be smart to use regular expressions to remove the scripts if the have been loaded already. (Credit to @JCOC611 for the idea of stripping tags.) Something like:

var usedScripts = {};

html = html.replace(/<script\s+src="([^"]+)"><\/script>/gi, function(str, file) {
    if(usedScripts[file]) {
        return "";
    } else {
        usedScripts[file] = true;
        return str;
    }
});

If you have a finite number of pages, what I prefer to do is have an object:

{
    myPage: {
        html:   'myhtml.html',
        script: 'myscript.js'
    }
}

Then have a loader function which simultaneously loads the script with document.createElement('script') and loads the page with HTML. You could easily check if that script has been used and skip loading.



来源:https://stackoverflow.com/questions/7781406/unload-external-js-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!