How can I insert a script into HTML head dynamically using JavaScript?
Asked
Active
Viewed 9.4k times
52
-
What server side language do you use? – Meligy Feb 27 '11 at 09:51
-
no server side language i want to use. – Wasim A. Feb 27 '11 at 09:55
-
using javascript at button click i want to insert into head. – Wasim A. Feb 27 '11 at 09:56
-
1Check this solution: http://unixpapa.com/js/dyna.html – eolith Feb 27 '11 at 09:57
3 Answers
80
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);

zackg
- 319
- 2
- 11

Bugs Bunny
- 2,496
- 1
- 26
- 32
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.

Peter Mortensen
- 30,738
- 21
- 105
- 131

Rajnikant
- 2,176
- 24
- 23
1
document.head.appendChild(document.createElement('script').setAttribute('src','http://ex.com/javascript.js'));

Sandesh B Suvarna
- 761
- 9
- 17
-
2This should not work since `setAttribute()` does not return the element: "Return Value: No return value" https://www.w3schools.com/jsref/met_element_setattribute.asp But you can put element in a variable `element`, then call `element.setAttribute(...)` and `appendChild(element)` – Frederic Leitenberger Jun 02 '17 at 09:02
-