6

Is it possible to create something that similar to:

var jsfile = "code....";
(a=(b=document).createElement('script')).src=jsfile;
b.body.appendChild(a);

where 'jsfile' is like an external js file but in our case will be a variable?

All of my tests failed and I succeeded to get the input of 'jsfile' but if there were function inside of obj (remember I want it to preform like an external js file) they didn't executed.

Example for a test:

var jsfile = "code....";
(a=(b=document).createElement('script')).text=(jsfile);
b.body.appendChild(a);
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Gorden Gram
  • 921
  • 2
  • 10
  • 14

2 Answers2

9

Try setting a type on the script element, like so (taken from Can't append <script> element):

var script   = document.createElement("script");
script.type  = "text/javascript";
script.src   = "path/to/your/javascript.js";    // use this for linked script
script.text  = "alert('voila!');"               // use this for inline script
document.body.appendChild(script);
Community
  • 1
  • 1
Ryan Lynch
  • 7,676
  • 1
  • 24
  • 33
6

Yes you can, actually, the src attribute is used only for a javascript file path, if you want to render the code you can use the innerText property:

var code = 'alert("working!")';
var script = document.createElement('script');
script.innerText = code;

document.body.appendChild(script);
udidu
  • 8,269
  • 6
  • 48
  • 68