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

Mark Rogers picture Mark Rogers · Jan 30, 2009 · Viewed 40.5k times · Source

I read that you should define your JavaScript functions in the <head> tag, but how does the location of the <script> (whether in the <head>, <body>, or any other tag) affect a JavaScript function.

Specifically, how does it affect the scope of the function and where you can call it from?

Answer

Simon_Weaver picture Simon_Weaver · Feb 3, 2009

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.