Can't append ')[0]; document.body.appendChild(script);`. – Simon East Jul 07 '17 at 04:04

  • Thanks! The `script.text` is just what I'm looking for, since I need some variables in there. – Espen Klem Aug 16 '19 at 13:39
  • 263

    I've seen issues where some browsers don't respect some changes when you do them directly (by which I mean creating the HTML from text like you're trying with the script tag), but when you do them with built-in commands things go better. Try this:

    var script = document.createElement( 'script' );
    script.type = 'text/javascript';
    script.src = url;
    $("#someElement").append( script );
    

    From: JSON for jQuery

    soumya
    • 3,801
    • 9
    • 35
    • 69
    acrosman
    • 12,814
    • 10
    • 39
    • 55
    24

    It is possible to dynamically load a JavaScript file using the jQuery function getScript

    $.getScript('http://www.whatever.com/shareprice/shareprice.js', function() {
      Display.sharePrice();
    });
    

    Now the external script will be called, and if it cannot be loaded it will gracefully degrade.

    Daniel Böhmer
    • 14,463
    • 5
    • 36
    • 46
    Cueball
    • 257
    • 2
    • 2
    21

    What do you mean "not working"?

    jQuery detects that you're trying to create a SCRIPT element and will automatically run the contents of the element within the global context. Are you telling me that this doesn't work for you? -

    $('#someElement').append('<script>alert("WORKING");</script>');
    

    Edit: If you're not seeing the SCRIPT element in the DOM (in Firebug for example) after you run the command that's because jQuery, like I said, will run the code and then will delete the SCRIPT element - I believe that SCRIPT elements are always appended to the body... but anyway - placement has absolutely no bearing on code execution in this situation.

    James
    • 109,676
    • 31
    • 162
    • 175
    • Amazing! There seems to be no vanilla native equivalent, but no despair as you can always [just load jQuery first](https://stackoverflow.com/a/58473770/4829915). – LWC Mar 11 '21 at 21:20
    18

    This works:

    $('body').append($("<script>alert('Hi!');<\/script>")[0]);
    

    It seems like jQuery is doing something clever with scripts so you need to append the html element rather than jQuery object.

    Darwin
    • 4,686
    • 2
    • 30
    • 22
    • 2
      THis is the only solution that works in my case. The other sol'ns above depend on javascript code present ahead of time in the html file. Since I'm adding code dynamically, such javascript code can't be known ahead of time! THANKS Darwin!! – tgoneil Nov 18 '13 at 19:15
    • [James' code](https://stackoverflow.com/a/611042/4829915) worked even better for me. Not only because it requires neither `$()`, `[0]`, nor escaping (e.g. `\/script`), but because the code here for some reason can't handle multiple tags (e.g, multiple scripts), while @James' can. – LWC Mar 11 '21 at 21:13
    14

    Try this may be helpful:

    var fileref=document.createElement('script');
    fileref.setAttribute("type","text/javascript");
    fileref.setAttribute("src","scriptAnalytics.js");
    document.getElementsByTagName("head")[0].appendChild(fileref);
    
    Jainul Khan
    • 349
    • 1
    • 3
    • 8
    • 9
      no idea why this guy negatives hes the only one not stupid enough to keep using jquery for everything! – SSpoke Mar 31 '14 at 08:07
    • Probably most of the answers uses jQuery because in the question the OP is using jQuery. – sanbor May 13 '17 at 17:37
    3

    I want to do the same thing but to append a script tag in other frame!

    var url = 'library.js'; 
    var script = window.parent.frames[1].document.createElement('script' ); 
    script.type = 'text/javascript'; 
    script.src = url;
    $('head',window.parent.frames[1].document).append(script);
    
    Julio
    • 1,903
    • 2
    • 16
    • 19
    3
    <script>
        ...
        ...jQuery("<script></script>")...
        ...
    </script>
    

    The </script> within the string literal terminates the entire script, to avoid that "</scr" + "ipt>" can be used instead.

    Roman Odaisky
    • 2,811
    • 22
    • 26
    • Or don't embed your javascript directly within the HTML document. External script files don't have this problem. – Ian Clelland Feb 09 '10 at 15:31
    • Escape sequences: `"\x3cscript\x3e\x3c/script\x3e"`. In XHTML, you only need to put in a commented-out CDATA block. – Eli Grey Apr 09 '10 at 00:58
    • 2
      It’s rather the `` that’s not allowed. See http://stackoverflow.com/questions/236073/why-split-the-script-tag-when-writing-it-with-document-write – Gumbo Jan 20 '11 at 17:40
    2

    Adding the sourceURL in the script file helped as mentioned in this page: https://blog.getfirebug.com/2009/08/11/give-your-eval-a-name-with-sourceurl/

    1. In the script file, add a statement with sourceURL like "//@ sourceURL=foo.js"
    2. Load the script using jQuery $.getScript() and the script will be available in "sources" tab in chrome dev tools
    Naga Kiran
    • 8,585
    • 5
    • 43
    • 53
    1

    Your script is executing , you just can't use document.write from it. Use an alert to test it and avoid using document.write. The statements of your js file with document.write will not be executed and the rest of the function will be executed.

    1

    This is what I think is the best solution. Google Analytics is injected this way.

    var (function(){
        var p="https:" == document.location.protocol ? "https://" : "http://";
            d=document,
            g=d.createElement('script'),
            s=d.getElementsByTagName('script')[0];
            g.type='text/javascript';
            g.src=p+'url-to-your-script.js';
            s.parentNode.insertBefore(g,s); })();
    
    dzona
    • 3,323
    • 3
    • 31
    • 47
    1

    You don't need jQuery to create a Script DOM Element. It can be done with vanilla ES6 like so:

    const script = "console.log('Did it work?')"
    new Promise((resolve, reject) => {
      (function(i,s,o,g,r,a,m){
          a=s.createElement(o),m=s.getElementsByTagName(o)[0];
          a.innerText=g;
          a.onload=r;m.parentNode.insertBefore(a,m)}
      )(window,document,'script',script, resolve())
    }).then(() => console.log('Sure did!'))
    

    It doesn't need to be wrapped in a Promise, but doing so allows you to resolve the promise when the script loads, helping prevent race conditions for long-running scripts.

    georgeawg
    • 48,608
    • 13
    • 72
    • 95
    vhs
    • 9,316
    • 3
    • 66
    • 70
    0

    Append script to body:

    $(document).ready(function() {
        $("<script>", {  src : "bootstrap.min.js",  type : "text/javascript" }).appendTo("body");
    });
    
    Cristian Olaru
    • 487
    • 5
    • 20
    0

    Another way you can do it if you want to append code is using the document.createElement method but then using .innerHTML instead of .src.

    var script = document.createElement( 'script' );
    script.type = 'text/javascript';
    script.innerHTML = 'alert("Hey there... you just appended this script to the body");';
    $("body").append( script );
    
    0

    I tried this one and works fine. Just replace the < symbol with that \x3C.

    // With Variable
    var code = "\x3Cscript>SomeCode\x3C/script>";
    $("#someElement").append(code);
    

    or

    //Without Variable
    $("#someElement").append("\x3Cscript>SomeCode\x3C/script>");
    

    You can test the code here.

    Andrew
    • 5
    • 5
    0

    Can try like this

    var code = "<script></" + "script>";
    $("#someElement").append(code);
    

    The only reason you can't do "<script></script>" is because the string isn't allowed inside javascript because the DOM layer can't parse what's js and what's HTML.

    VipinKundal
    • 442
    • 6
    • 14
    0

    I wrote an npm package that lets you take an HTML string, including script tags and append it to a container while executing the scripts

    Example:

    import appendHtml from 'appendhtml';
    
    const html = '<p>Hello</p><script src="some_js_file.js"></script>'; 
    const container = document.getElementById('some-div');
    
    await appendHtml(html, container);
    
    // appendHtml returns a Promise, some_js_file.js is now loaded and executed (note the await)
    

    Find it here: https://www.npmjs.com/package/appendhtml

    Lukas
    • 9,752
    • 15
    • 76
    • 120
    0
    /* SELECTOR */
    
    
    $T = document.getElementsByTagName.bind( document );
    
    
    /* INCLUDE */
    
    
    function include( file_js )
    {
        // Create script
        var s       = document.createElement( "script" );
            s.src   = file_js;
            s.type  = "text/javascript";
            s.defer = true;
    
        // Append script
        $T( "head" ).item(0).appendChild( s );
    }
    
     /* TEST CODE */
    
    
    <script>
        include( "<? echo ROOT ?>/lib/js/test.js" ); // Test.js contains: console.log( "Hello World" );
    </script>
    
    
    /* RESULT (in Google Chrome DevTool: Elements) */
    
    
        <script src="http://localhost/mysite/lib/js/test.js" type="text/javascript" defer></script>
    </head>
    
    
    /* RESULT (in Google Chrome DevTool: Console) */
    
    
    Hello World
    

    Defer attribute: a script that will be downloaded in parallel to parsing the page, and executed after the page has finished parsing:

    Starboy
    • 109
    • 5
    -1

    Just create an element by parsing it with jQuery.

    <div id="someElement"></div>
    <script>
        var code = "<script>alert(123);<\/script>";
        $("#someElement").append($(code));
    </script>
    

    Working example: https://plnkr.co/edit/V2FE28Q2eBrJoJ6PUEBz

    sanbor
    • 1,264
    • 15
    • 20