How can I insert a script into HTML head dynamically using JavaScript? [duplicate]
Asked Answered
S

3

52

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

Stilu answered 27/2, 2011 at 9:50 Comment(4)
What server side language do you use?Polynomial
no server side language i want to use.Stilu
using javascript at button click i want to insert into head.Stilu
Check this solution: unixpapa.com/js/dyna.htmlElba
A
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);
Anlage answered 20/3, 2014 at 13:34 Comment(1)
An explanation would be in order.Justification
O
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.

Overbalance answered 19/8, 2016 at 12:36 Comment(0)
I
1
document.head.appendChild(document.createElement('script').setAttribute('src','http://ex.com/javascript.js'));
Indebted answered 15/5, 2016 at 2:34 Comment(2)
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)Comment
An explanation would be in order.Justification

© 2022 - 2024 — McMap. All rights reserved.