Question

I wonder wheter a javascript block/function is allways available once loaded. Because I've tested something and now I'm a bit confused. I defined a script block into a div. The script block has an event-handling function for an element to reload the div with ajax. The ajax call returns plain html of the div and replaces it with current one. But it means to replace the script which makes the execution also. I've tought that the script would been cut-out of execution after replace statement. But it didn't. Code lines after replace statement been executed So how this stuffs work. How do you describe life-time of a script block?

Was it helpful?

Solution

When the code contained in a script element is evaluated, the result of that code evaluation becomes part of the runtime environment of the page. Removing the script element does not remove the resulting structures (functions, etc.) from the environment.

So if the script defines functions, or hooks event handlers to elements, or creates new properties on existing objects (including the global object), those functions, handlers, and properties remain in memory even if the script that defined them is removed from the DOM (subject to the usual JavaScript garbage collection; e.g., objects not referenced anywhere are eligible for GC, but the script element has no bearing on that). The script element is merely a mechanism for conveying the code to the browser.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top