52

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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Wasim A.
  • 9,660
  • 22
  • 90
  • 120

3 Answers3

80
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
  • 11
Bugs Bunny
  • 2,496
  • 1
  • 26
  • 32
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,738
  • 21
  • 105
  • 131
Rajnikant
  • 2,176
  • 24
  • 23
1
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