http://www.w3schools.com/js/js_whereto.asp
This link is to a JavaScript tutorial on w3schools. The page says that
a script put in the HEAD is executed only when called, whereas one put
in the BODY is executed as the page loads (implying invariably, whether
called or not).
To test, I tried the following two pages:
<HTML>
<HEAD>
<SCRIPT>
<!--
document.write("I am a statement and I reside in the HEAD tag of
this page.")
-->
</SCRIPT>
</HEAD>
<BODY>
<SCRIPT>
<!--
document.write("I am a statement and I reside in the BODY tag of
this page.")
-->
</SCRIPT>
</BODY>
</HTML>
Both of them executed. So, I thought the statement made in that
tutorial must pertain to functions declared in JavaScript. To test it,
I tried another file:
<HTML>
<HEAD>
<SCRIPT langauge="JavaScript" type="text/javascript">
<!--
void function foo()
{
document.write("I'm function foo() and I reside in the HEAD tag of
this page.");
}
//-->
</SCRIPT>
</HEAD>
<BODY>
<SCRIPT langauge="JavaScript" type="text/javascript">
<!--
void function bar()
{
document.write("I am function bar() and I reside in the BODY tag of
this page.");
}
//-->
</SCRIPT>
</BODY>
</HTML>
In this, none of the functions exectued. Then I called each one of them
and they executed, implying the following as per my tests:
1. If a snippet of JavaScript code is written outside a function, and
is not tied to the event of an HTML control, it will execute
invariably. The time it will execute will be determined on its sequence
in the file and it will be executed in the sequence the page loads. It
doesn't matter where the snippet is put -- the HEAD or the BODY tag;
and
2. If a snippet of JavaScript code is embedded inside a function, it
will not be executed, no matter where it is put -- HEAD or BODY, unless
it is explicitly called or triggered by the occurance of the event it
is tied to.
Please reconcile the learning I got from my test with that given in the
tutorial. I am confused.