views:

37

answers:

2

According to the discussion comments here: http://api.jquery.com/append/ the .append() of a script evaluates the script, then discards it. IF the script adds jQuery behavior such as for example:

$('#mything').click().addClass('hasclass');

is that event management retained (espcially if complex chaining gets added), or discarded, and more importantly, if it IS discarded does cleanup happen or are there potential leaks there?

Are there examples of best practices regarding this type of script management?

+1  A: 

Side effects of scripts run from dynamically added content are not removed. (It would probably be impossible for the library to do that even if it wanted to.)

As to "best practices", there's not really any management work to be done. If you pull in page fragments via ajax, then you either want scripts to be run or you don't; it all depends on how your site works.

Pointy
+1  A: 

All the effects of the script remain, no matter how complex the chanining. Remember that the script has to be fully executed before it's thrown away, so everything it rigs up, etc are there, it created JavaScript objects/handlers, anything that references them...still references them.

Objects won't be removed or garbage collected as long as they're referenced, so all those handlers, etc will work normally. I'd personally steer clear of this type of scripting because it's not explicit, and leaks a bit in older IE versions, but there's nothing "wrong" with it outright.

Nick Craver
Well, jQuery will clean up handlers etc. when elements are subsequently removed from the DOM, regardless of what sort of `<script>` block added them, no?
Pointy
@Pointy - That's not what it's cleaning up in this case though, it's actually removing the `<script>` block itself, and actually it's the browser doing this in it's `.innerHTML` implementation (for example, this is the same reason you can't see the `<head>` children in an ajax load with Firefox/Chrome but you can in Opera after calling `$(data)`). But in *other* cases, such as `.remove()` and `.empty()`, yes those clean up their entries in `$.cache`.
Nick Craver
Doesn't jQuery's "html()" API pull out the script blocks itself, before it hands the content to `innerHTML`? I recall seeing that when I was looking into the weird behavior of ".load()" when you include a selector after the URL. (It strips out the scripts and *doesn't* run them.)
Pointy