Appending Scripts To Head Using Javascript - Weird Behavior
Solution 1:
You're laboring under a false assumption: It doesn't matter whatsoever whether script
elements are in the head
or body
, they get run regardless. Moving them after they've been appended to the DOM is at best pointless, and at worst may cause unfortunate side-effects if the script is re-run when moved (but I don't think it is).
As for why you're seeing the behavior you're seeing, it's because getElementsByTagName
returns a liveNodeList
. When you move a script, it gets removed from the NodeList
. So given your four scripts, you'll get back a NodeList
initially containing four elements, so .length
is 4
and [0]
is your first script. When you move that script out of the div
, the NodeList
is updated because the script is no longer in the div
, so its length is now 3
and [0]
refers to your second script (the one loading jQuery).
You can avoid having this behavior interrupt your loop in two ways:
Loop backward, from
.length - 1
to0
inclusive, orTurn the
NodeList
into an array, so the elements aren't moved out from under you.
Post a Comment for "Appending Scripts To Head Using Javascript - Weird Behavior"