How can I insert a script into HTML head dynamically using JavaScript?
83,169
Solution 1
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);
Solution 2
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.
Solution 3
document.head.appendChild(document.createElement('script').setAttribute('src','http://ex.com/javascript.js'));
Related videos on Youtube
Author by
Wasim A.
[email protected] | Skype:wasimxe | Whatsapp: +923455407008
Updated on May 20, 2020Comments
-
Wasim A. about 4 years
How can I insert a script into HTML head dynamically using JavaScript?
-
Meligy over 13 yearsWhat server side language do you use?
-
Wasim A. over 13 yearsno server side language i want to use.
-
Wasim A. over 13 yearsusing javascript at button click i want to insert into head.
-
eolith over 13 yearsCheck this solution: unixpapa.com/js/dyna.html
-
-
Frederic Leitenberger about 7 yearsThis 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 variableelement
, then callelement.setAttribute(...)
andappendChild(element)
-
Peter Mortensen about 4 yearsAn explanation would be in order.
-
Peter Mortensen about 4 yearsAn explanation would be in order.