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.
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:
If you have a finite number of pages, what I prefer to do is have an object:
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.