开发者

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

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开发者_如何学JAVA 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.


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.

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

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

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜