Mark Schultheiss
Mark Schultheiss

Reputation: 34168

jQuery .append() and script behavior and management

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?

Upvotes: 0

Views: 200

Answers (2)

Nick Craver
Nick Craver

Reputation: 630379

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.

Upvotes: 1

Pointy
Pointy

Reputation: 413702

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.

Upvotes: 1

Related Questions