Have a complex client-side template system where resources are loaded via XHR (as strings) and then injected into DOM.
For Javascript insertion up until now we were dynamically creating script tags and appending them to the DOM, not only for speed in modern browsers but also because this makes it possible to cleanup/remove the scripts once the template is not needed any more.
However – it seems that in older browsers and IE (even the latest 10 version) in particular window.eval() is a lot faster in evaluating code than just injecting it via new tags – like 10x as fast. Even IE-native execScript is a lot slower than eval.
I’d try optimizing it to use eval for performance gain in IE, however I don’t see any way to reference or/and remove such evaluated Javascript afterwards. If anyone has any ideas on how to go about this – would appreciate it.
I think you may be misunderstanding something there. Removing a
scriptelement does not remove the script it contained from the JavaScript context it was loaded into: http://jsbin.com/ujiratIt’s exactly the same as script loaded via
scripttags: The only way to “unload” it is to remove all references to it, which makes it eligible for garbage collection. The best way to do that is to have your scripts define a single, global symbol that contains all of the functionality of that script, e.g.:You can then “unload” that by doing:
…provided it doesn’t give out references to itself that that doesn’t clean up (such as setting up event handlers or other closures).