How can I insert a script into HTML head dynamically using JavaScript?
-
What server side language do you use?Meligy– Meligy2011-02-27 09:51:45 +00:00Commented Feb 27, 2011 at 9:51
-
no server side language i want to use.Wasim A.– Wasim A.2011-02-27 09:55:40 +00:00Commented Feb 27, 2011 at 9:55
-
using javascript at button click i want to insert into head.Wasim A.– Wasim A.2011-02-27 09:56:03 +00:00Commented Feb 27, 2011 at 9:56
-
1Check this solution: unixpapa.com/js/dyna.htmlagranjo– agranjo2011-02-27 09:57:20 +00:00Commented Feb 27, 2011 at 9:57
Add a comment
|
3 Answers
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);
1 Comment
Peter Mortensen
An explanation would be in order.
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
document.head.appendChild(document.createElement('script').setAttribute('src','http://ex.com/javascript.js'));
2 Comments
Frederic Leitenberger
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)Peter Mortensen
An explanation would be in order.