How to dynamically insert a <script> tag via jQuery after page load?

Doug picture Doug · Oct 4, 2010 · Viewed 237.8k times · Source

I'm having problems getting this to work. I first tried setting my script tags as strings and then using jquery replaceWith() to add them to the document after page load:

var a = '<script type="text/javascript">some script here</script>';
$('#someelement').replaceWith(a);

But I got string literal errors on that var. I then tried encoding the string like:

var a = '&left;script type="text/javascript"&gt;some script here&lt;\/script&gt;';

but sending that to replaceWith() outputs just that string to the browser.

Can someone please let me know how you would go about dynamically adding a <script> tag into the browser after page load, ideally via jQuery?

Answer

Rocket Hazmat picture Rocket Hazmat · Oct 4, 2010

You can put the script into a separate file, then use $.getScript to load and run it.

Example:

$.getScript("test.js", function(){
    alert("Running test.js");
});