views:

93

answers:

4

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?

+3  A: 

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");
});
Rocket
thanks, but will that stick it into the DOM? i realize i left out that important info, that i need the script tag to be inserted into the DOM, evaluated, at which point it returns 3rd party ad code to display on our site in a specific <div>.
Doug
`$.getScript` will just load a .js file via AJAX and execute it. The script doesn't need to be in the DOM to be able to access a div on your page.
Rocket
A: 

ignore this answer ;)

Doug
Hi @Doug - when you want to expand on your question, it's best to edit it directly and not add an answer. Also you may want to read up on [how to use the markdown system](http://stackoverflow.com/editing-help).
Pointy
A: 

If you are trying to run some dynamically generated javascript, you would be slightly better off by using eval. However, JavaScript is such a dynamic language that you really should not have need for that.

If the script is static, then Rocket's getScript-suggestion is the way to go.

Magnar
A: 

Try the following:

<script type="text/javascript">
// Use any event to append the code
$(document).ready(function() 
{
    var s = document.createElement("script");
    s.type = "text/javascript";
    s.src = "http://scriptlocation/das.js";
    // Use any selector
    $("head").append(s);
});

Credits: link text

first comment.

Link-