且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

添加< script>元素到DOM并有JavaScript运行?

更新时间:2023-09-29 22:32:40

我不知道YUI的 Node.create()函数可以工作,所以对此没有评论。但是一个简单的跨浏览器脚本是:

pre $ window $ on $ = function(){
var s = document。的createElement( '脚本');
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);


try..catch 块是必要的,因为大多数浏览器都喜欢第一种方法,但有些则不会抛出错误。第二种方法涵盖那些。您也可以简单地 eval 代码,它或多或少是等价的,以及一些库的功能。


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

I did this with 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.

Someone knows what the problem is?

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

  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..catch block 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 eval the code, which is more or less equivalent and what some libraries do.