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

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


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);

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'));