javascript document.createElement('script').src = 变量?是否可以?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12805212/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 17:09:54  来源:igfitidea点击:

document.createElement('script').src = variable? is it possible?

javascriptjavascript-events

提问by Gorden Gram

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?

其中 'jsfile' 就像一个外部 js 文件,但在我们的例子中是一个变量?

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.

我的所有测试都失败了,我成功地获得了 'jsfile' 的输入,但是如果 obj 中有函数(记住我希望它像外部 js 文件一样执行),它们没有执行。

example for a test:

测试示例:

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

回答by Ryan Lynch

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

尝试在脚本元素上设置类型,如下所示(取自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);

回答by udidu

Yes you can, actually, the srcattribute is used only for a javascript file path, if you want to render the code you can use the innerTextproperty:

是的,实际上,该src属性仅用于 javascript 文件路径,如果要呈现代码,可以使用该innerText属性:

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

document.body.appendChild(script);