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?
The position in the source is irrelevant - only the position in time matters. You should avoid putting scripts in the <head> if possible as it slows down page display (see the link Alan posted).
The <script> tag is used to embed a client-side script (JavaScript). The <script> element either contains scripting statements, or it points to an external script file through the src attribute. Common uses for JavaScript are image manipulation, form validation, and dynamic changes of content.
The <script> Tag In HTML, JavaScript code is inserted between <script> and </script> tags. You can place any number of scripts in an HTML document. Scripts can be placed in the <body> , or in the <head> section of an HTML page, or in both.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With