最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - document.createElement('script').src = variable? is it possible? - Stack Overflow

programmeradmin2浏览0评论

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

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);
Share Improve this question edited Feb 13, 2023 at 13:25 Brian Tompsett - 汤莱恩 5,88372 gold badges61 silver badges133 bronze badges asked Oct 9, 2012 at 17:25 Gorden GramGorden Gram 9812 gold badges11 silver badges14 bronze badges 2
  • 1 Can you please clarify what you're asking. I really can't tell. I see no problem in your code. – I Hate Lazy Commented Oct 9, 2012 at 17:31
  • Have you looked at this question? stackoverflow.com/questions/610995/… – Ryan Lynch Commented Oct 9, 2012 at 17:31
Add a comment  | 

2 Answers 2

Reset to default 10

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

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);
发布评论

评论列表(0)

  1. 暂无评论