Javascript 如何将 <script> 元素添加到 DOM 并执行其代码?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6432984/
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-08-23 21:42:18  来源:igfitidea点击:

How to add a <script> element to the DOM and execute its code?

javascripthtml

提问by ajsie

I want to add a element into the existing DOM to have the javascript code run.

我想在现有的 DOM 中添加一个元素来运行 javascript 代码。

I did this with YUI:

我用 YUI 做到了这一点:

var scriptNode = Y.Node.create('<script type="text/javascript" charset="utf-8">alert("Hello world!");<\/script>');
var headNode = Y.one('head');
headNode.append(scriptNode);

It's successfully added to the DOM but it doesn't give me an alert.

它已成功添加到 DOM 但它没有给我警报。

Someone knows what the problem is?

有人知道问题是什么吗?

回答by RobG

I have no idea how YUI's Node.create()function works, so no comment on that. But a simple cross-browser script is:

我不知道 YUI 的Node.create()功能是如何工作的,所以对此不予评论。但是一个简单的跨浏览器脚本是:

  window.onload = function() {
    var s = document.createElement('script');
    s.type = 'text/javascript';
    var code = 'alert("hello world!");';
    try {
      s.appendChild(document.createTextNode(code));
      document.body.appendChild(s);
    } catch (e) {
      s.text = code;
      document.body.appendChild(s);
    }
  }

The try..catchblock is necessary as most browsers like the first method but some don't and throw an error. The second method covers those. You can also simply evalthe code, which is more or less equivalent and what some libraries do.

在try..catch块是必要的,因为大多数浏览器,如第一种方法,但有些却没有,并抛出一个错误。第二种方法涵盖了这些。您也可以简单地评估代码,这或多或少与某些库的功能相同。

回答by Flip

I found this function in the JQuery source, which seems to do what you want and feels a bit cleaner than the other approaches to me. But then again I am a JS beginner and probably don't see the details. Anyways, somebody might take something useful away from this.

我在 JQuery 源代码中找到了这个函数,它似乎可以做你想做的事情,而且感觉比我的其他方法更简洁。但话又说回来,我是一个 JS 初学者,可能看不到细节。无论如何,有人可能会从中拿走一些有用的东西。

function DOMEval( code, doc ) {
    doc = doc || document;

    var script = doc.createElement( "script" );

    script.text = code;
    doc.head.appendChild( script ).parentNode.removeChild( script );
}