Home  >  Article  >  Web Front-end  >  Analysis of the difference between placing JS code in head and body_javascript skills

Analysis of the difference between placing JS code in head and body_javascript skills

WBOY
WBOYOriginal
2016-05-16 17:58:511180browse

So what's the difference? Let’s look at an example first:
A two-level cascading dynamic drop-down list box, with a first-level category (i.e. large category) id="vSort0".

Copy code The code is as follows:


function changelocation(id)
{…………}


………………


Now there is a js Script:
Copy code The code is as follows:



So should this js script be placed in the head or the body?
The answer is not only to put it in the body, but also to put it behind the list box with id='vSort0' defined, because this js script has document.form4.vSort0.selectedIndex. If it is placed in the head or body Before id='vSort0', the code is executed sequentially after the page is loaded. When the js is executed, it is found that vSort0 is undefined (i.e. undefind), and the js loses its function.
Why do we often see so many people putting js scripts in the head? right!
It’s because the js code you see in the head has onclick and other events that pass variables to the function.
This tells us that if we want to define a global object, and this object is related to a button (etc.) on the page, we must put it in the body. The reason is obvious: if we put it in the head , then when the page loads the head part, the button (etc.) has not been defined yet (it can also be said that it has not been loaded, because the loading process is the process of executing the code, including the definition), you can get It can only be an undefind.
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn