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'));
Share:
83,169

Related videos on Youtube

Wasim A.
Author by

Wasim A.

[email protected] | Skype:wasimxe | Whatsapp: +923455407008

Updated on May 20, 2020

Comments

  • Wasim A.
    Wasim A. about 4 years

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

    • Meligy
      Meligy over 13 years
      What server side language do you use?
    • Wasim A.
      Wasim A. over 13 years
      no server side language i want to use.
    • Wasim A.
      Wasim A. over 13 years
      using javascript at button click i want to insert into head.
    • eolith
      eolith over 13 years
      Check this solution: unixpapa.com/js/dyna.html
  • Frederic Leitenberger
    Frederic Leitenberger about 7 years
    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
    Peter Mortensen about 4 years
    An explanation would be in order.
  • Peter Mortensen
    Peter Mortensen about 4 years
    An explanation would be in order.