HTML script tags can not be atomic/self-closing
Recently I completed a project where I converted an Actionscript form generation system I wrote for my wife's business into Javascript.
I've been writing Javascript on and off for the last, almost, 20 years. For easy coding, I started with all my code and css styles in the same html file, but eventually broke up everything into individual files.
I placed the stylesheet in its own file and loaded it using a standard <link> tag:
<link id="primaryStylesheet" rel="stylesheet" type="text/css" href="path/to/my/fancy/stylesheet.css" />
Notice how the I used the self-closing (atomic) version of the <link> tag (ends with "/>" rather than with a closing "</link>").
Then it was time to load in all the Javascript which was now in its own set of external files. I used a standard <script> tag for that:
<!-- DOESN'T WORK --> <script type="text/JavaScript" src="/awesome/library.js" />
However, I was surprised to find that while my stylesheet loaded without a problem, my Javascript files did not. I knew this not because I got an error like "Javascript files did not load", but because the scripts that I knew to work and do something on screen no longer did anything. After a little investigation, I discovered they weren't in memory at all.
A little googling brought me to an entry on Siderite's Blog that explains he had the same problem and discovered that the W3C DOM recommendation states the following about the script tag:
Start tag: required, End tag: required
Thus, it can't be an atomic/self-closing tag. Browsers respect that, though they don't provide any error feedback, instead failing silently.
<!-- Works! --> <script type="text/JavaScript" src="/awesome/library.js"></script>
So, thanks Siderite for reminding me that it pays to read specs. :-)
4 comments
Comments are closed. These were left on the previous version of this site. Questions? Get in touch.
For backward compatibility--or to fail gracefully--I'll still continue to use the non-atomic version of the script tag.
Self-closing syntax (/>) used on a non-void HTML element. Ignoring the slash and treating as a start tag.
According to the XHTML and HTML5 specs (your link references the HTML4 spec), either is actually valid, but it just happens that the major browser implementations require a separate close tag. This is unfortunately an example of another place in web programming where you CAN'T code to the spec, you have to code to the implementations.