Thursday, September 16, 2004

IE Gotcha! Do Not Use Self-Closing Script Tag

I recently had the (ahem) pleasure of helping a colleague debug a JavaScript problem. The issue was the he had multiple JavaScript blocks on a page like this:

<script type='text/JavaScript' src='uitools.js' />
<script type='text/JavaScript'>
function DoSomething() {
//...
}
</script>

Seems harmless enough, right? For the longest time we could not determine why DoSomething was not accessible to page elements. We tried all kinds of things until we stumbled upon a surprising resolution. We began to drill in on the issue when I moved the DoSomething function into the upper script block (which required breaking open the self-closing script tag). Suddenly, page elements could use the function successfully. After we moved the function back to its rightful home, everything still worked. Then I realized that the only difference was that the upper script block was no longer self-closing. When I converted it back to self-closing, sure enough the page stopped working again.

For some reason IE (and possibly other browsers) does not handle self-closing script tags in an XML compliant manner. Go figure!

No comments: