Daily Archives: October 3, 2007

innerHTML and SCRIPT tags

I have a requirement where I get some HTML snippet through Ajax request and then update a div area. So far so good. The HTML snippet needed to have some javascript (so that I could display a date as per the user’s timezone). That’s when the trouble started.

After a bit of research, came to the conclusion that

div.innerHTML = some-string-containing-script-tags;

doesn’t work. Some one mentioned about using <\/script> instead of </script> but that didn’t work for me though there was a reply to the suggestion that it worked! Then there is an interesting hack on how to achieve the same. While this is a cool hack, I didn’t wanted to do it.

So, by trail and error, in Firefox 2.0, it seemed to work by doing the following.

var div = document.createElement('div');
div.innerHTML = htmlFromAjaxResponse;
var children = div.childNodes;
actualDivToBeUpdated.innerHTML = "";
for(var i=0;i<children.length;i++)

This worked in Firefox 2.0. The script in the original response HTML did get executed. (note though not to use document.write in the script. Instead, you have to manipulate the DOM).

The same technique didn’t work in IE though.

Update: As per microsoft making a script tag marked with DEFER attribute makes it possible to execute script by setting it through innerHTML. I tried and it worked. However, I now have the problem that the DOM node that’s inserted using the innerHTML doesn’t seem to be available by the time the script is executing even though the script is placed after the dom node.

Update 2: Finally got it working on both Firefox and IE. The problem with the DOM manipulation mentioned above is, in case of IE, after marking the script to DEFER, it is executed for the DIV element whose innerHTML is set. Since I am creating the DIV brand new, it’s not yet within the DOM, so trying to use getElementById in the script from the document is causing the problem. So, I had to introduce a dummy DIV element in the initial document and then it worked. However, for Firefox, the dummy element idea doesn’t work. It has to be a new element to create the DOM. Since that DOM is copied to the actual node as per the code shown above, at that time the script gets executed fine. So, I ended up writing browser specific code, but finally it seems to work for both browsers.


Filed under AJAX, DHTML, javascript