I know, that there are already similar topics on SO, and the answer to them is usually "you can use eval(), but you shouldn't do this". Great answer, but anyway eval() doesn't solve my problem. Let's say I have a String var called string_code:
var GLOBAL_TEST= 'it works';
alert(GLOBAL_TEST);
Now I need to execute it. Note, that it should also define GLOBAL_TEST, so it can be used later on. Using jQuery, I do it like this:
$('body').append('<script>'+string_code+'</script>');
Now, how to do it in pure JS?
-
https://developer.mozilla.org/en-US/docs/Web/API/document#MethodsBrett– Brett2013年08月26日 23:10:16 +00:00Commented Aug 26, 2013 at 23:10
-
1Doing this is actually no safer than using eval. The reason eval is dangerous is because it executes what could be potentially volatile code. Any content from outside your script might contain dangerous code which may compromise the sites security. By creating a script like this, the browser runs the code just like you could using eval. Any dangerous code would still get executed.Metod Medja– Metod Medja2013年08月26日 23:13:38 +00:00Commented Aug 26, 2013 at 23:13
1 Answer 1
very simply create the <script> element and set its innerHTML property, then append it to the body:
var s;
s = document.createElement('script');
s.innerHTML = 'alert("works");';
//or in your case
//s.innerHTML = string_code;
document.body.appendChild(s);
Just be aware that this is generally considered a bad practice, adding scripts dynamically is usually done with external scripts along the lines of:
var s;
s = document.createElement('script');
s.src = 'path/to/script.js';
s.onreadystatechange = s.onload = function () {...};
document.getElementsByTagName('head')[0].appendChild(s);
2 Comments
$('body').append('<script>'+string_code+'</script>'); causes the HTML parser to end the script prematurely. Your code doesn't have the closing script tag in it, so it's OK