How to dynamically insert a – Pointy Oct 04 '10 at 18:05

  • @Rocket's answer is the best, but if you definitely wanted to add inline script from a string, then you would just pass it to the `eval()` function. But use of `eval()` almost always suggests that there's a better way of doing what you are trying to do. – Nick Oct 04 '10 at 18:07
  • we're trying to postpone loading of 3rd party ads until the end of the page. those ads get called via 2 script tags, so i wanted to run a function after page load that throws them in dynamically. – Doug Oct 04 '10 at 18:08
  • In that case Rocket's answer is definitely what you want. – Nick Oct 04 '10 at 18:10
  • 2
    Not all third-party scripts are designed to be deferrable. If the script uses `document.write` and you call it after page loading it will destroy the page. – bobince Oct 04 '10 at 18:13
  • @bobince - yes, i did manage to once get this to work but noticed the page seemed to get reloaded and just display the ad. it seems you might be right, their script has a few .write methods. so essentially, when these scripts are in the page loading along with it, they just output the ad code within the page, but if loaded after page load, they overwrite the page completely instead? – Doug Oct 04 '10 at 18:20
  • 1
    Why not import those tags in ` – Pointy Oct 04 '10 at 18:42
  • Perhaps worth noting that here in 2023 all browsers default the type so we no longer need the `type="text/javascript"` for ` – Mark Schultheiss Jan 30 '23 at 13:30
  • 9 Answers9

    108

    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");
    });
    
    gen_Eric
    • 223,194
    • 41
    • 299
    • 337
    • 3
      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
      .
      – Doug Oct 04 '10 at 18:14
    • 1
      `$.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. – gen_Eric Oct 04 '10 at 18:17
    • 6
      But with `$.getScript()` the script will need to be on the same domain or both the remote domain and the browser will need to support `CORS`. – hippietrail Aug 10 '12 at 17:50
    • 14
      @hippietrail That's actually not true. It just inserts a plain ol' script tag, which doesn't require CORS or same-domain. I use this to shorten the code for loading Google Analytics for example, and it loads just fine. Behind the scenes the actual jquery code that runs is pretty similar to the GA snippet, in fact. – Chris Moschini May 22 '13 at 01:38
    • @ChrisMoschini: Hmm I can't remember back when I commented on this. I don't actually used `$.getScript()` but don't want to delete my comment since it now has four upvotes... – hippietrail May 22 '13 at 02:38
    • 42
      Since the answer from @hippietrail will attract the most attention with its 4 upvotes, it should be made emphatically clear that he is incorrect. As the jQuery docs highlight in their `$.ajax` notes: "Script and JSONP requests are not subject to the same origin policy restrictions." [source](http://api.jquery.com/jQuery.ajax/). In other words, **`$.getScript` can pull .js files from other domains, not just your own**. – EleventyOne Aug 31 '13 at 19:46
    • 1
      Another nice trick is to use chaining and run $.getScript(url).done(function(script, textStatus) { console.log('done')}).fail(function(jqxhr, settings, exception) { console.log('error')}); – zmonteca Dec 02 '13 at 22:44
    • 1
      This is overly complicated as it requires a separate .js file when all the OP wants to do is inject some script into the DOM. – jcoffland Nov 23 '14 at 21:48
    • @RocketHazmat, just a question, it is also possible to use this for a CDN script? e.g. http://cdnjs.cloudflare.com/ajax/libs/waypoints/2.0.3/waypoints.min.js – Franco Jul 03 '16 at 22:45
    • @Franco: Yes, you can do `$.getScript('http://cdnjs.cloudflare.com/ajax/libs/waypoints/2.0.3/waypoints.min.js');`. – gen_Eric Jul 05 '16 at 14:02
    73

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

    http://api.jquery.com/append

    isherwood
    • 58,414
    • 16
    • 114
    • 157
    Bassem
    • 3,135
    • 2
    • 25
    • 41
    • 4
      +1 for use of `append` to add a script. Append causes even inline script to evaluate immediately (just what I needed). Thanks – iCollect.it Ltd Apr 23 '13 at 08:54
    • 1
      I end up having a lot of issues in IE8/9 with this approach. Namely Stack Overflow errors. I resorted to the $.getScript() method below to have this work across the board. – zmonteca Dec 02 '13 at 22:46
    • 1
      Yes @jcoffland this was written in October 2010 :) – Bassem Nov 25 '14 at 13:07
    • If the page containing this code is loaded using AJAX, the browser will throw a "Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience" warning. – Rajshekar Reddy Feb 03 '16 at 11:20
    • @Reddy Great comment. This was posted in October 2010, I'm sure by now this method is no longer a valid/recommended approach, users have to proceed at their own discretion. – Bassem Feb 09 '16 at 23:19
    • Does this solution work if the injected javascript is using `document.write`? I ask this because most ad related javascripts we get from customers are using it. – basZero Sep 21 '16 at 12:17
    42

    Here's the correct way to do it with modern (2014) JQuery:

    $(function () {
      $('<script>')
        .attr('type', 'text/javascript')
        .text('some script here')
        .appendTo('head');
    })
    

    or if you really want to replace a div you could do:

    $(function () {
      $('<script>')
        .attr('type', 'text/javascript')
        .text('some script here')
        .replaceAll('#someelement');
    });
    
    jcoffland
    • 5,238
    • 38
    • 43
    14

    A simpler way is:

    $('head').append('<script type="text/javascript" src="your.js"></script>');
    

    You can also use this form to load css.

    iman
    • 21,202
    • 8
    • 32
    • 31
    • 8
      You might want to avoid putting the string `` in your source though since it may cause parsing problems: http://stackoverflow.com/questions/236073/why-split-the-script-tag-when-writing-it-with-document-write – jacobq Apr 29 '15 at 15:49
    • 6
      escaping the last `/` did the trick for me: `$('head').append(' – jerik Jun 07 '16 at 20:14
    6

    This answer is technically similar or equal to what jcoffland answered. I just added a query to detect if a script is already present or not. I need this because I work in an intranet website with a couple of modules, of which some are sharing scripts or bring their own, but these scripts do not need to be loaded everytime again. I am using this snippet since more than a year in production environment, it works like a charme. Commenting to myself: Yes I know, it would be more correct to ask if a function exists... :-)

    if (!$('head > script[src="js/jquery.searchable.min.js"]').length) {
        $('head').append($('<script />').attr('src','js/jquery.searchable.min.js'));
    }
    
    ddlab
    • 918
    • 13
    • 28
    • btw. I do the same with stylesheets: if (!$('head > link[href="widgets/css/widgets.css"]').length) {$('head').append($('').attr('rel','stylesheet').attr('href','widgets/css/widgets.css'));} – ddlab Mar 14 '16 at 14:37
    5

    Here is a much clearer way — no need for jQuery — which adds a script as the last child of <body>:

    document.body.innerHTML +='<script src="mycdn.js"><\/script>'
    

    But if you want to add and load scripts use Rocket Hazmat's method.

    Note: it willl cancel declared event listeners.

    Gagik
    • 169
    • 2
    • 11
    2

    Example:

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

    It should work. I tried it; same outcome. But when I used this:

    var length = 1;
    var html = "";
    for (var i = 0; i < length; i++) {
        html += '<div id="codeSnippet"></div>';
        html += '<script type="text/javascript">';
        html += 'your script here';
        html += '</script>';
    }
    $('#someElement').replaceWith(a);
    

    This worked for me.

    Edit: I forgot the #someelement (btw I might want to use #someElement because of conventions)

    The most important thing here is the += so the html is added and not replaced.

    Leave a comment if it didn't work. I'd like to help you out!

    L84
    • 45,514
    • 58
    • 177
    • 257
    1

    There is one workaround that sounds more like a hack and I agree it's not the most elegant way of doing it, but works 100%:

    Say your AJAX response is something like

    <b>some html</b>
    <script>alert("and some javscript")
    

    Note that I've skipped the closing tag on purpose. Then in the script that loads the above, do the following:

    $.ajax({
        url: "path/to/return/the-above-js+html.php",
        success: function(newhtml){
            newhtml += "<";
            newhtml += "/script>";
            $("head").append(newhtml);
        }
    });
    

    Just don't ask me why :-) This is one of those things I've come to as a result of desperate almost random trials and fails.

    I have no complete suggestions on how it works, but interestingly enough, it will NOT work if you append the closing tag in one line.

    In times like these, I feel like I've successfully divided by zero.

    Mike Lyons
    • 1,748
    • 2
    • 20
    • 33
    Boyan
    • 456
    • 3
    • 16
    • 3
      It will not work if the closing script tag is in one piece as the browser sees it as the closing tag for your script instead of a string literal. – iCollect.it Ltd Apr 23 '13 at 08:52
    • 1
      `<\/script>` would be valid though – S P Sep 03 '13 at 07:11
    • I think @TrueBlueAussie's point was in response to your comment "Just don't ask me why...but interestingly enough, it will NOT work if you append the closing tag in one line." He explained why so that any readers who would like a better answer than "I don't know" could more easily find it. See also: http://javascript.crockford.com/script.html – jacobq Apr 29 '15 at 15:56
    • 1
      @Sathvik is correct, according to that link. Ash's comment seems to have been a reply to one that got removed. – Arlen Beiler Jan 26 '16 at 11:45
    -4

    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 a need for that.

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

    albert
    • 8,112
    • 3
    • 47
    • 63
    Magnar
    • 28,550
    • 8
    • 60
    • 65