document.write and dynamic script injection in Internet Explorer

I have recently run into an issue in all versions of IE (i.e. IE6, IE7 and IE8) when I used document.write to insert a Javascript file onto the page. This is what I was trying to accomplish:

<script type="text/javascript">
document.write('<div id="ad1" style="display:none;">');
document.write('<script type="text/javascript" src="http://someadagency.com/somead?params"><\/script>');
document.write('</div>');
</script>

The problems was that in IE, this is what I get:

<div id="ad1" style="display:none;"></div>[ad content]

Where in Firefox and Safari, I get:

<div id="ad1" style="display:none;">[ad content]</div>

Which is the expected behavior I want. After plenty of online research, I found out that IE defers the processing of any script tag inserted in the document using document.write until it's done processing the parent script tag. To circumvent this problem, I externalized the markup I wanted to wrap the ad in and now my cross-browser solution is:

<script type="text/javascript">
document.write('<script type="text/javascript" src="http://mydomain.com/js/pre_ad_wrapper.js"><\/script>');
document.write('<script type="text/javascript" src="http://someadagency.com/somead?params"><\/script>');
document.write('<script type="text/javascript" src="http://mydomain.com/js/post_ad_wrapper.js"><\/script>');
</script>

Where the content of the two files is basically the one-line document.write statement spitting out the wrapping markup.

I'm using this technique to load in 3rd-party ads at the bottom of the page and relocating them to their propers spots on window load. This has proved to be a major performance boost, especially combined with the other techniques we're using to renders the page.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s