Self-closing script tags and XHTML

Wednesday, March 9, 2011

Today, I started playing around with jQuery, and, of course, ran into a problem I ran into before and, of course, forgot the solution to.

Basically, this code didn’t work in my web page:

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

There was no error, but none of my scripts on the page ran. I undid my changes one by one and eventually found out this should have been:

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

In other words: the script tag should have been explicitly closed.

I try to use XHTML, of course, so I more or less automatically made the tag self-closing, but for some reason this caused a problem.

An excellent discussion on StackOverflow eventually led me to a W3C document that explained not only why this happens, but also contains many recommendations for writing good HTML/XHTML compatible markup.

The problem boiled down to a content type mismatch. My web page, though adhering to XHTML standards, was still interpreted as HTML by the browser. XHTML requires that tags like <br/> and <img/> get an extra slash to make them self-closing.

However, these are tags that can never have any content. <br>text</br> is illegal; same with <img>. Tags that may contain content (like <script>!) should not be treated this way – HTML expects a separate closing tag, because it essentially ignores the self-closing slash. Bottom line: use self-closing tags for tags without content (<br>, <img>, <hr>, <link>, <meta>) but not for tags that may contain content. So there.

Anyway, now I understand this I probably won’t forget it again, and the W3C document is a worthwhile read at any rate.