Any idea why the piece of code below does not add the script element to the DOM?
var code = \"\";
$(\"#someElement\").append(cod
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.
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.
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
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.
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/
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.