Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to know life-time of a script block or javascript code?

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?

like image 830
Halil Ibrahim Avatar asked Mar 07 '13 09:03

Halil Ibrahim


1 Answers

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.

like image 157
T.J. Crowder Avatar answered Oct 01 '22 14:10

T.J. Crowder