Skip to content Skip to sidebar Skip to footer

Appending Scripts To Head Using Javascript - Weird Behavior

The problem I'm trying to solve is an ad loading script, that loads the ad code with jsonp and inserts it into the dom. Now sometimes the ad code will include javascript tags, and

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:

  1. Loop backward, from .length - 1 to 0 inclusive, or

  2. Turn 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"