如何从字符串而不是文件向头标记添加动态javascript?

Vin*_*mes 5 javascript

我使用Javascript生成其他自定义JavaScript,然后将其添加到HEAD标记.下面的代码很好地添加了一个javascript文件,但是如果脚本是刚生成的变量呢?

var scriptTag = document.createElement("script");
scriptTag.setAttribute("type", "text/javascript");
scriptTag.setAttribute("src", "myfile.js");
document.getElementsByTagName("head")[0].appendChild(scriptTag);
Run Code Online (Sandbox Code Playgroud)

感谢您的关注.

I H*_*azy 4

   // script text
var txt = "alert('foo');";

var scriptTag = document.createElement("script");
scriptTag.setAttribute("type", "text/javascript");

   // append it in a text node
scriptTag.appendChild(document.createTextNode(txt));
document.getElementsByTagName("head")[0].appendChild(scriptTag);
Run Code Online (Sandbox Code Playgroud)

FWIW,您不需要为此使用脚本标记。您可以改用Function构造函数。

var txt = "alert('foo');";

Function(txt)();
Run Code Online (Sandbox Code Playgroud)