How can I insert a script into HTML head dynamically using JavaScript?
Asked
Active
Viewed 8.4k times
49
-
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
79
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
- 10
Bugs Bunny
- 2,319
- 1
- 24
- 31
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,030
- 21
- 100
- 124
Rajnikant
- 1,841
- 18
- 20
3
document.head.appendChild(document.createElement('script').setAttribute('src','http://ex.com/javascript.js'));
Sandesh B Suvarna
- 745
- 8
- 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
-