How does the location of a script tag in a page affect a JavaScript function that is defined in it?

Telling people to add <SCRIPT> only in the head sounds like a reasonable thing to do, but as others have said there are many reasons why this isn’t recommended or even practical – mainly speed and the way that HTML pages are generated dynamically.

This is what the HTML 4 spec says :

The SCRIPT element places a script
within a document. This element may
appear any number of times in the HEAD
or BODY of an HTML document.

And some sample HTML. Doesn’t it look pretty all formatted here 🙂

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
     "http://www.w3.org/TR/html4/strict.dtd">
<HTML>
<HEAD>
<TITLE>A document with SCRIPT</TITLE>
<META http-equiv="Content-Script-Type" content="text/tcl">
<SCRIPT type="text/vbscript" src="http://someplace.com/progs/vbcalc">
</SCRIPT>
</HEAD>
<BODY>
<SCRIPT type="text/javascript">
...some JavaScript...
</SCRIPT>
</BODY>
</HTML>

And something to look forward to in HTML 5 :

New async attribute in <SCRIPT> :

Note: There are ways [sic] a script can be
executed:

The async attribute is “true”: The
script will be executed asynchrously
with the rest of the page, so the
script will be executed while the page
continues the parsing.

The async attribute is “false”, but
the defer attribute is “true”: The
script will be executed when the page
is finished with the parsing.

Leave a Comment