49

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

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
Wasim A.
  • 9,201
  • 21
  • 89
  • 117

3 Answers3

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'));
  • 2
    This 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
  • An explanation would be in order. – Peter Mortensen May 19 '20 at 11:28