Place JavaScript code

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.