add script dynamically javascript code example

Example 1: javascript dynamicly include another js file

var script = document.createElement('script');
script.src = "https://www.examplesite/myscript.js";
document.head.appendChild(script);

Example 2: dynamically add script code to page

var newScript = document.createElement("script");
newScript.src = "http://www.example.com/my-script.js";
target.appendChild(newScript);

Example 3: dynamically add script code to page

var newScript = document.createElement("script");
var inlineScript = document.createTextNode("alert('Hello World!');");
newScript.appendChild(inlineScript); 
target.appendChild(newScript);