That annoying non-self-closing <script> tag

This is a stupid hack and you shouldn't do it. But it was one of those things where I wondered if it would work and had to try it.

One of the things that annoys me tremendously about HTML is that you can't write a self-closing script tag. E.g.

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

is invalid. The <script> element is not allowed to be empty because it may contain inline code, and HTML is not smart enough to turn that feature on or off based on the presence of an attribute. (And it probably shouldn't be.) So you have to do <script ... ></script> every time.

On the other hand, HTML does have an excellent tag for including references to outside resources: the <link> tag, and it can be self-closing. It's already used to include stylesheets, RSS and Atom feeds, canonical URIs, and all sorts of other goodies. Why not Javascript?

No browser supports loading Javascript via a <link> tag, so you have to cheat a little.

<html>
<head>
    <link rel="script" type="text/javascript" href="/jstest.js" />
</head>

<body>
....
<script type="text/javascript">
    var i=document.getElementsByTagName('link');
    for(j=0;j<i.length;j++){var e=i[j];  e.rel=='script'?e.type=='text/javascript'?document.write('<scr'+'ipt type="text/javascript" src="'+e.href+'"></scr'+'ipt>'):1:1;}
 </script>

</body>

This bit of golfed Javascript simply iterates through every <link> tag in the document, checks if they have rel="script" and type="text/javascript" attributes, and then dynamically inserts the appropriate <script> tag to actually include them. You can hide this bit of ugliness at the bottom of your HTML, and have nice pretty <link> tags up top.

Of course, you shouldn't actually use this for anything, ever.

BTW, wouldn't it be nifty if HTML had a foot tag to complement head and body? It would be useful for including things that need to be there after the rest of the document is processed, instead of sticking them at the bottom of the body section.

Leave a comment

About Mike Friedman

user-pic Mike Friedman is a professional computer programmer living and working in the New York City area.