How to append <script></script> in JavaScript?

JavascriptJqueryAppendAppendchild

Javascript Problem Overview


I need to use appendChild() or jQuey's append() to append some <script> tag stuff into the document. From what I can tell, this is getting stripped out. Anyone know how to do it?

Javascript Solutions


Solution 1 - Javascript

// Create the element

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

// Add script content

script.innerHTML = "...";

// Append

document.head.appendChild(script);

Or

document.body.appendChild(script);

Solution 2 - 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.

Solution 3 - Javascript

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

DEMO

Solution 4 - Javascript

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

Solution 5 - Javascript

This worked for me..

<script>
    $('head').append("<script>your script content here<\/script>");
</script>

Note that the "/" of the inner </script> has been escaped to be "<\/script>". If it is not, it actually closes the outer <script> tag.

The script added wont be visible but will get executed. Hope that helps.

Solution 6 - Javascript

$('your_document_selector').text('<script></script>')

.text() makes it possible to append script tags with it being rendered as HTML.

OR

$('your_document_selector').append('&lt;script&gt;&lt;/script&gt;')

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDavidView Question on Stackoverflow
Solution 1 - JavascriptDennisView Answer on Stackoverflow
Solution 2 - JavascriptSapan DiwakarView Answer on Stackoverflow
Solution 3 - JavascriptqwertymkView Answer on Stackoverflow
Solution 4 - JavascriptNicola PeluchettiView Answer on Stackoverflow
Solution 5 - JavascriptSuganyaView Answer on Stackoverflow
Solution 6 - JavascriptlinuxeasyView Answer on Stackoverflow