Can't append [removed] element

后端 未结 18 2187
被撕碎了的回忆
被撕碎了的回忆 2020-11-21 06:11

Any idea why the piece of code below does not add the script element to the DOM?

var code = \"\";
$(\"#someElement\").append(cod         


        
相关标签:
18条回答
  • 2020-11-21 06:39

    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.

    0 讨论(0)
  • 2020-11-21 06:40

    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.

    0 讨论(0)
  • 2020-11-21 06:40

    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

    0 讨论(0)
  • 2020-11-21 06:42

    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.

    0 讨论(0)
  • 2020-11-21 06:44

    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
    0 讨论(0)
  • 2020-11-21 06:44

    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.

    0 讨论(0)
提交回复
热议问题