Site Navigation

Thursday, October 4, 2007

bug 142 - appendChild doesn't work on a script tag in IE

Issue: #142
Affects: IE6, IE7, IE8 Beta 1, IE8 Beta 2, IE8 PR1, IE8 RC1

Using the DOM to generate elements is ideal, but when you want to generate a script tag, you can't use the DOM in IE.

Example:

<script type="text/javascript">
var scriptTag = document.createElement('script');
scriptTag.appendChild( document.createTextNode('var now = new Date();alert(now.getTime());') );
var bodyTag = document.getElementsByTagName('body')[0];
bodyTag.appendChild( scriptTag );
</script>


In all browsers except IE, this will append a script element to the page, with code as the content.


Known Workarounds: One. For IE, we have to divert from the spec., and use the .text property instead.

Example Workaround Code:

<script type="text/javascript">
var scriptTag = document.createElement('script');
scriptTag.text = 'var now = new Date();alert(now.getTime());';
var bodyTag = document.getElementsByTagName('body')[0];
bodyTag.appendChild( scriptTag );
</script>



Related Issues: None.