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

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.

Leave a Comment