john walker
john walker

Reputation: 35

Execute JavaScript code from String (pure JS)

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?

Upvotes: 1

Views: 411

Answers (1)

zzzzBov
zzzzBov

Reputation: 179046

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

Upvotes: 2

Related Questions