How can I insert a script into HTML head dynamically using JavaScript?
How can I insert a script into HTML head dynamically using JavaScript? [duplicate]
Asked Answered
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.html –
Elba
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);
An explanation would be in order. –
Justification
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.
document.head.appendChild(document.createElement('script').setAttribute('src','http://ex.com/javascript.js'));
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.