Reminiscing about the history of the <script> tag ritual

When JavaScript was first introduced, browsers treated the contents of script tags as regular content. To be Netscape 1.0 compatible, you had to add HTML comments. Even though the comments became unnecessary in the mid 1990s, they are STILL used in many places around the web today.

Then along came XHTML. Script tag content could contain entities such as ampersands. Although browsers in HTML mode parsed the content fine, it was not valid XML. So add a CDATA declaration, and you can put any content inside the script tag.

XHTML was seen as the future of the web. It was theoretically faster because browsers could be sure there were no HTML errors before parsing.

In the mid 2000s there was a strange push for uber compatibility and HTML standards guru Ian Hickson proposed an extremely ambitious approach that combined HTML comments with XML comments.

In the late 2000s people started to realize that using XHTML wasn’t really that helpful and that comments weren’t necessary. The type attribute had been optional since the mid 1990s and people started to drop it. So you were left with a bare script tag. How liberating!

In 2010 it became the best practice to use Immediately-Invoked Function Expressions (IIFE) as coined by “Cowboy” Ben Alman. Basically you wrap the body of your JavaScript in an anonymous function that is immediately executed. It took two more lines but was less likely to cause conflicts.

And finally we have the way of 2013. In addition to IIFE, we can add the string "use strict"; to the function body and the code would be error-checked. At development time, potential errors were easy to pinpoint. Older browsers see "use strict"; as a string literal that is never used; it has no effect. For other browsers, it triggers a mode that will throw errors for such things as missing var keywords.

What next?

  • There are also defer and async attributes that can be very useful.
  • You might start seeing "use asm"; in addition to "use strict";. asm will help speed up execution and will be especially useful to libraries that do low-level processing such as processing video feeds. It is backward compaitble with older JavaScript; it mostly consists of adding +, ||, and other symbols to tell the compiler how to optimize.
  • You may see the language attribute come back to support native use of languages like Coffescript and TypeScript.

And who knows what will come up next.