1. Put it in the head
This method loads js Code before the page is manned. In this way, we cannot obtain webpage elements in the head because the webpage has not been loaded. Let's look at the example below, when we want to dynamically modify the value displayed by the button, the code in the head will report a Cannot
Set property 'value' of null error. When debugging this error in chrome, an error 'document. getElementById (...) 'is null or not an object will be reported in IE. Of course, if you put the js Code in the body, it will be okay.
[Html]
<Html>
<Head>
<Script type = "text/javascript">
Document. getElementById ('click _ click'). value = 'click me! ';
Function show_message (){
Alert ('Hello! ');
}
</Script>
</Head>
<Body>
<Input id = "click_button" type = "button" value = "Click me! "Onclick =" show_message () ">
<Script type = "text/javascript">
Document. getElementById ('click _ click'). value = 'click me! ';
</Script>
</Body>
</Html>
2. Put it in the body
Execute the js script according to the placement sequence. For example, in the above example, if we put js before loading elements, an error will also be reported.
[Html]
<Html>
<Head>
</Head>
<Body>
<Script type = "text/javascript">
Document. getElementById ('click _ click'). value = 'click me! ';
</Script>
<Input id = "click_button" type = "button" value = "Click me! "Onclick =" show_message () ">
</Body>
</Html> www.2cto.com
Tip: When the js file is large, it is recommended to load the js file before </body>. This will not affect the loading speed of the webpage. If it is placed in the header, loads the js file first.
Author: lixiang0522