Defering Inline JavaScript Problems

I came across an interesting problem trying to debug a website that had issues with some ad code earlier. The site was working fine until ad code had been added, then in Internet Explorer it was only showing the ad instead of the page. Firefox, Safari and Chrome were fine, so it suggested a problem with the ad code.

The ad code in question was pretty common, the sort that inserts a script tag via a document.write.

<script language="javascript" defer="defer" async >
<!--
if (window.adgroupid == undefined) {
window.adgroupid = Math.round(Math.random() * 1000);
}
document.write('>scr'+'ipt language="javascript1.1" src="http://adserver.adtech.de/addyn|3.0|311.0|3328078|0|225|ADTECH;cookie=info;alias=FindClassicCars+Maserati+7+leaderboard;loc=100;target=_blank;key=key1+key2+key3+key4;grp='+window.adgroupid+';misc='+new Date().getTime()+'"></scri'+'pt>');
//-->
</script>

The problem turned out to be with the attribute defer in the script tag.

Defer gives the browser a clue that a piece of JavaScript can be run later, rather than as soon as the browser sees it. This can be used to speed up the rendering of a site. However, Internet Explorer runs differently to other browsers. As the script in question was inline, all the other browsers ran it immediately, whereas Internet Explorer didn’t. On Internet Explorer the code was run once the page DOM had been created, so writing out the fresh tags after the document was closed. This caused the ads to show on what looked like a new page on IE’s below version 9, and on IE 9 the ads appeared at the bottom of the page.

The fix is to simply remove the defer attribute and change the the opening script tag to the following, leaving the rest of the ad tag in place.

<script type="text/javascript">

You may have noticed I’ve ignored the async attribute that was in the original script tag. That’s an interesting new attribute in HTML5, but alas a topic for another time.

Leave a Reply