52

How can I insert a script into HTML head dynamically using JavaScript?

4
  • What server side language do you use? Commented Feb 27, 2011 at 9:51
  • no server side language i want to use. Commented Feb 27, 2011 at 9:55
  • using javascript at button click i want to insert into head. Commented Feb 27, 2011 at 9:56
  • 1
    Check this solution: unixpapa.com/js/dyna.html Commented Feb 27, 2011 at 9:57

3 Answers 3

83
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.onload = function() {
    callFunctionFromScript();
}
script.src = 'path/to/your-script.js';
head.appendChild(script);
Sign up to request clarification or add additional context in comments.

1 Comment

An explanation would be in order.
6

Here is how I injected a function on the fly without any source file, etc.

document.head.appendChild(document.createElement('script').text = 'function LogIt(msg) { console.log(msg);}' );

And to inject to body

document.body.appendChild(document.createElement('script').text = 'function LogIt(msg) { console.log(msg);}' );

After executing this, if you try LogIt('hello');, you should see 'hello' in the console.

Comments

1
document.head.appendChild(document.createElement('script').setAttribute('src','http://ex.com/javascript.js'));

2 Comments

This should not work since setAttribute() does not return the element: "Return Value: No return value" w3schools.com/jsref/met_element_setattribute.asp But you can put element in a variable element, then call element.setAttribute(...) and appendChild(element)
An explanation would be in order.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.