I am facing a dilemma and seeking advice on the best approach to deal with it. While developing a single-page web application, I have implemented a system where pages are dynamically loaded via ajax, requiring each page to have its own corresponding javascript file.
However, I noticed that these page-specific javascript files are adding variables to the global javascript space, potentially impacting memory usage. To counteract this, I have started reusing common variable names and setting specialized variables to null in my global ajax loader function.
Now, I am contemplating adding a 'release()' function to each page to clear out these variables before unloading the page. My questions are:
Is the impact of leaving a few Kb of unused RAM significant enough to warrant this level of optimization?
Are there better strategies for managing and cleaning up global variables in javascript?
Is my current method effective, and does JavaScript garbage collection handle unreferenced memory as expected?
Followup after Giacomo's answer:
I appreciate Giacomo's solution, which seems to work seamlessly with my setup. However, I am unsure how exactly it manages to clean up the local variables once the page is unloaded. While everything appears to function correctly, I remain uncertain about the underlying process of memory allocation and release.
Considering this, I propose the following solution for discussion:
//executed upon ajax page load after insertion into DOM
var pageData = {
someData: 999,
someArray: ["one","two"],
functionOne: function(arg) {
//perform tasks
},
functionTwo: function(arg) {
//perform tasks
}
};
//manipulate data
pageData.functionOne(pageData.someData);
pageData.functionTwo("abc");
//called before page is removed from DOM
function releasePage() {
pageData = null;
}
//Javascript garbage collection eventually clears the memory