Forcing IE to accept script tags in innerHTML

So, my first blog post, and instead of Perl, I'm writing about Javascript.

I'm using a common idiom:

  • AJAX call returns HTML with embedded script tags
  • create a temporary <div>
  • div.innerHTML = request.responseText
  • move the children of the div to the appropriate spot
Firefox conveniently executes the script texts. Opera and Safari require extra steps to execute the script contents (eg, globalEval in jquery), and IE does whatever the hell it pleases.

IE usually works with globalEval, except when it doesn't.  I found that if the AJAX response was just a single script tag, then IE would filter it out.  But script tags were being created in certain circumstances.

Long story short, if you need to return a single <script> tag, wrap it in a <form> tag.  For whatever reason, IE will then accept it as innerHTML and create the script node, which you can then execute with globalEval or similar

Leave a comment

About Clinton Gormley

user-pic The doctor will see you now...