JS in HeadCodeIt will be read before the page is loaded, and the JS Code in the body will be read after the whole page is loaded.
So what is the difference? Let's take a look at an example:
A list of level-2 cascade dynamic drop-down lists with level-1 category id = "vsort0 ".
< Head >
Function changelocation (ID)
{............}
</ Head >
< Body > < Select Class = "Input1" ID = "Vsort0" Name = "Vsort0" Onchange = "Changelocation (document. form4.vsort0. Options [document. form4.vsort0. selectedindex]. Value );" Style = "Width: 100px ;" > ...... Omitted ...... </ Select >
..................
</ Body >
There is a JS script:
<Script language = "JavaScript">
Changelocation (document. form4.vsort0. Options [document. form4.vsort0. selectedindex]. value );//Initialize the second-level category of the first level-1 category. The second-level category of the first level-1 category is not displayed after the page is loaded. Select back to display. Pass the value of a level-1 category to the changelocation () function to generate a list of level-2 categories.
</SCRIPT>
So should I put this JS script in the head or in the body?
The answer is not only to put it in the body, but also to the definition.Id = 'vsort0'Because the JS script containsDocument. form4.Vsort0. SelectedindexIf the code is executed sequentially after the page is loaded before the head or body id = 'vsort0 'and the js code is executed, vsort0 is undefind ), this JS is useless.
Why do we often see that it is okay to put JavaScript scripts in the head? Yes!
It is because the JS Code in the head contains onclick and other events that pass variables to the function.
This tells us that if we want to define a global object that is related to a button (and so on) on the page, we must put it into the body. The principle is obvious: if you put the head in, when the page loads the head part, the button (and so on) has not been defined (it can be said that it has not been loaded yet, because the loading process is the process of executing the Code, including the definition), you can only get an undefind.