How to Append <script></script> in javascript?

Try this:

var s = document.createElement("script");
s.type = "text/javascript";
s.src = "http://somedomain.com/somescript";
$("head").append(s);

Note that the script will load and you can access the variables inside it, but you wouldn't see the actual <script> tag in the DOM.


// Create the element

var script = document.createElement("script");

// Add script content

script.innerHTML = "...";

// Append

document.head.appendChild(script);

Or

document.body.appendChild(script);

$('<script>alert("hi");</' + 'script>').appendTo(document.body);

DEMO


If you need to append a script so that it's parsed you could do as google does for his +1 button

  (function() {
    var po = document.createElement('script');
    po.type = 'text/javascript';
    po.async = true;
    po.src = 'link to your script here';
    var s = document.getElementsByTagName('script')[0];
    s.parentNode.insertBefore(po, s);
  })();