« Creationist on a Thread: Part IParenthood, Part II »

JavaScript Script Tags Violate Normal Tag Rules

03/08/12

  12:02:02 pm, by Nimble   , 217 words  
Categories: Programming

JavaScript Script Tags Violate Normal Tag Rules

You know how you can - for just about every HTML tag - combine the start and end tags, XML-style, into just one node?

For example, you need not go <img src="mypig.jpg"></img> - you can simply go <img src="mypig.jpg"/>.

It turns out that this is not the case for <script> tags at all, at least not without special treatment.

I had a fairly simple page to which I was trying to add a JavaScript include, a snippet of which went like this:

<script type="text/javascript" src="../js/dialogs.js" />
<script type="text/javascript">
function initPage() {
.. rest of function ..

Then, later on in the page, I tell the body to run initPage when it loads:

<body onload="initPage()" ...

When I showed the web page, I got the error:

SCRIPT5007: The value of the property 'initPage' is null or undefined, not a Function object

How could that possibly be?

As it turned out, that JavaScript inclusion did not seem to consider the script block finished... or something. Everything worked again when I changed that line to this:

<script type="text/javascript" src="../js/dialogs.js" ></script>

Now there's a twist. Apparently, this is the case when the web page gets sent back with the 'normal' HTTP header Content-Type: text/html. If it is sent back with application/xhtml+xml instead, then the start and end script tags no longer have to be broken up. See here.

No feedback yet