Justin
Justin

Reputation: 566

How do I insert a script tag in to the top/beginning of head tag?

I want to insert a script tag before all the rest of the scripts in the head tag. How would I do that with native javascript?

<head>
    //INSERT SCRIPT HERE
     <script type="text/javascript" src="common.js"></script>
     <script type="text/javascript" src="omni-controls.js"></script>
</head>

When I use this, it just appends after all the tags in the head tag.

document.getElementsByTagName("head")[0].appendChild(script);

Upvotes: 9

Views: 19426

Answers (3)

Craig1123
Craig1123

Reputation: 1560

document.head.insertBefore(script, document.head.firstElementChild);

Upvotes: 5

Quentin
Quentin

Reputation: 943579

Get the firstChild of the <head>, and then use insertBefore.

This won't change the order scripts are loaded in though (since you'll be inserting it into the DOM after other scripts have been parsed), so this won't give any significate difference from just using appendChild

Upvotes: 6

I Hate Lazy
I Hate Lazy

Reputation: 48761

var head = document.getElementsByTagName("head")[0]

head.insertBefore(script, head.firstChild);

Upvotes: 18

Related Questions