5

For reasons too complicated to get into now, I have an ajax call that returns some dynamically created Javascript that I want to inject into my page. The following code works on Chrome, but not in IE:

 var node = document.getElementsByTagName("head")[0] || document.body;
  if (node)
  {
    var script = document.createElement("script");
    script.type = "text/javascript";
    //script.innerHTML = json.javascript;
    var textnode = document.createTextNode(json.javascript);
    script.appendChild(textnode);
    node.appendChild(script);
  }

In IE, I get "SCRIPT65535: Unexpected call to method or property access." As you can see from the commented out code, before I tried the textnode, I tried just inserting it with script.innerHTML. That also worked in Chrome, but in IE I got "SCRIPT600:Unknown runtime error".

Is there a way to stick some javascript into the DOM in IE?

Paul Tomblin
  • 179,021
  • 58
  • 319
  • 408
  • You are probably better off using jquery since you won't have to worry about certain features implemented differently in IE. – scartag Jan 02 '13 at 01:38
  • If you know of a way to do this with jQuery, please let me know. $(node).html isn't working any better than script.innerHTML. – Paul Tomblin Jan 02 '13 at 01:39
  • Maybe this helps: http://stackoverflow.com/questions/8610574/inserting-and-executing-conditional-javascript – regulatethis Jan 02 '13 at 01:40
  • @regulatethis, both the solutions on that question use innerHTML, which doesn't work in IE. – Paul Tomblin Jan 02 '13 at 01:42
  • 1
    Looks like there are some security restrictions with IE, here is a discussion about it. http://stackoverflow.com/questions/703705/how-do-i-inject-javascript-to-a-page-on-ie-8 – specialscope Jan 02 '13 at 01:42

1 Answers1

6

And of course, as soon as I post this, I find http://www.phpied.com/dynamic-script-and-style-elements-in-ie/

  var node = document.getElementsByTagName("head")[0] || document.body;
  if (node)
  {
    var script = document.createElement("script");
    script.type = "text/javascript";
    script.text = json.javascript;
    node.appendChild(script);
  }
Paul Tomblin
  • 179,021
  • 58
  • 319
  • 408