IE8 javascript not running from script element in head

July 17th, 2011 | by Sean |

After staring at other people’s solutions to this problem for a day or so, I finally realised what I was doing wrong and thought I’d better share it, just in case you also fail to see for several hours how you caused the problem. I have a page that works nicely in Firefox, Chromium, Opera etc and fired up an old copy of WinXP on VirtualBox to check the site worked okay in IE. I wanted to show it to someone whose website was obviously written by and for users of Microsoft software, so was gutted to see a horribly broken page or, when I tried various hacks to see what was happening, no page at all.

To cut a long story short, the problem was caused by me emitting a SCRIPT element in the document’s HEAD that looked like this:

<script src="/static/js/shipping-methods.js" type="text/javascript" />

when it should be this:

<script src="/static/js/shipping-methods.js" type="text/javascript"></script>

The former (empty element) works just fine in every browser I have but IE8, the latter (block element) works in every browser including IE8.

Now that I’ve figured out what the problem is, it’s easy enough to find a web-page with the answer (and several comments recalling the pain this problem caused for them) such as “Why don’t self-closing script tags work?” at Stack Overflow. Reading through the comments – far enough – makes me think “D’oh! Of course!”. My site’s pages are served as XHTML unless the user-agent is IE, in which case my XHTML-generating code includes these headers:

X-XHTML-HTML-Hack: http://www.w3.org/TR/xhtml-media-types/#media-types
Content-Type: text/html; charset=UTF-8

The problem is that the self-closing element (or whatever you like to call it – I have Java classes that generate such things with names varying on a theme of EmptyElement, but I see pages that suggest that’s something different) is valid in XHTML but not in HTML. IE gets content from the server which it is told is HTML and silently fails to parse the self-closing element, trashing the page in the process.

So now I know. Beware the self-closing script element in XHTML pages sent with the text/html kludge to Microsoft browsers.

Post a Comment