In my role, I am responsible for managing a Content Management System (CMS) used by developers to create content that involves JavaScript. In the past, we placed the content in an iFrame for containment purposes; now, it operates as a single-page client-side application where JavaScript is directly inserted into the main window.
The current content library was developed inefficiently, so I am working to address the risk of a cluttered window object or memory leaks after multiple pages of content have been loaded and viewed.
One approach I am considering is wrapping the JavaScript code with a self-executing function or a similar method, setting it to 'undefined' and deleting it as needed (for reference). However, the challenge lies in needing to inject the wrapper before the script execution, ruling out a straightforward ajax call for the script tag. This leaves me with the option of appending the wrapper to the JavaScript code as a string and utilizing eval, which may not be ideal but could be necessary in this scenario.
For instance, if the original .js file includes the following code:
var global = true;
It would then be transformed into:
(function() {
var global = true;
})();
This ensures that the variable is no longer globally accessible.