codeRambler Ramblings on code, the web, and technology

How do I use the <script> tag?
Friday December 23rd 2005, 3:20 pm
Filed under: Javascript, Web development

I use Javascript every day in my web projects – and have often been asked for details on how to use the <script> tag correctly. The W3C have a formal description of the <script> tag which includes a summary of the required (and optional) attributes.

In the past, browsers have used various techniques to handle the <script> contents… and this has had a long lasting effect on the way we use this tag in our current projects. The most abused attribute remains in common use today (even though has been deprecated in HTML 4.01 and XHTML 1.0 Strict) – the language attribute. Instead of specifying the language, it is now standard to specify the MIME type through use of the type attribute – and it is important to note that this is the only required attribute for the <script> tag.

Inline Javascript

If you are including some Javascript in the document itself, then you would use a construct similar to this:

<script type="text/javascript">
alert("Hello world!");

If you are delivering this content in a document that is using an XHTML doctype, then you should comment the data between the <script> tags (if you are unable to include it as an external Javascript file – see below) so that it is not parsed client-side. In the past you would often see a similar technique in use to “hide the code from older browsers” (note that the following example shows the correct way to use comments in an XHTML document using CDATA):

<script type="text/javascript">
alert("Hello world!");

There is no point using the CDATA comments above in a non-XHTML page at all. Nor is there any value in using the following kind of comments (whether you are working on an HTML or an XHTML document). This commenting was widely used to prevent “old browsers” seeing the Javascript. Nobody uses these “old browsers” for regular web use (and if they did, most web sites that use Javascript would break anyway)… so there is absolutely no point in including the comments:

<script type="text/javascript">
alert("Hello world!");

Linked Javascript

If you are including an external Javascript file in the document, then you would use a construct similar to this:

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

The only difference between inline and linked Javascript is that the latter uses the src attribute to specify where the linked Javascript file resides.

Setting a default scripting language

When writing well formed documents, you should include information about the default scripting language. This can be done using a meta tag in the document:

<META http-equiv="Content-Script-Type" content="text/javascript">

This is good practice, but is not required – especially if the server is already serving linked Javascript files as “text/javascript” (or more correctly: “text/x-javascript”).

Comments Off