How can I unload a JavaScript resource with all its defined objects from the DOM?
Im developing a simple framework that enables to load html fragments into a "main" html. Each fragment is self contained and may include references to additional JS and CSS files. The JS and CSS resources are parsed and dynamically added to the html. When the fragment is removed/replaced from the DOM I want to remove its JS and CSS.
If I remove the script element in the example below, the functions defined in page1.js are still available.
<html> <head> <script src="page1.js" type="text/javascript"></script> </head> <body> ...
Is there a way to unload page1.js objects from the DOM?
========= The test code I use =======
I tried the advice i got in the comments below; to delete the added objects using a cleanup function - but even this fails. The sources i used for testing:
<html> <head> <script type="text/javascript"> function loadJSFile(){ var scriptTag = document.createElement("script"); scriptTag.setAttribute("type", "text/javascript"); scriptTag.setAttribute("src", "simple.js"); var head = document.getElementsByTagName("head")[0]; head.appendChild(scriptTag); } function unloadJSFile(){ delete window.foo; delete window.cleanup; alert("cleanedup. typeof window.foo is " + (typeof window.foo)); } </script> </head> <body> Hello JavaScript Delete <br/> <button onclick="loadJSFile();">Click to load JS</button> <br/> <button onclick="foo();">call foo()</button> <br/> <button onclick="unloadJSFile();">Click to unload JS</button> </body> </html>
simple.js source:
var foo = function(){ alert("hello from foo"); }
The unload event fires when a document has completely unloaded. Typically, the unload event fires when you navigate from one page to another. The unload event is fired after: beforeunload event.
The unload event occurs when the user navigates away from the page. The unload event is triggered when: a link to leave the page is clicked. a new URL is typed in the address bar.
This cannot be done.
When a script is executed, function definitions are added to the global window
object. There may be debugging symbols attached to the function that indicate where the function came from, but this information is not available to scripts.
About the only way you could achieve something like this would be to create a pseudo-namespace in the script and then throw away that whole namespace when you are done with it. However, this question hints to me that you are trying to do something the wrong way. Perhaps elaborating on your scenario would help us provide alternate solutions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With