Home  >  Article  >  Web Front-end  >  Where to place JavaScript code

Where to place JavaScript code

高洛峰
高洛峰Original
2016-11-26 13:20:351276browse

1. Put it in the head
This method will load the js code before the page is loaded. In this case, we cannot get the web page elements in the head because the web page has not been loaded yet. See the example below, when we want to dynamically modify the button When displaying the value, the code in the head will report a Cannot
set property 'value' of null error. This error is obtained when debugging in chrome. In IE, an error will also be reported that 'document.getElementById(...)' is empty or not an object. Of course, if you put the js code in the body, there will be no problem.
[html]








2. Place it in the body
and execute the js scripts in the order of placement. For example, in the above example, if we put js before the element is loaded, an error will also be reported.
[html]







www.2cto.com

Tip: When the js file is relatively large, it is recommended to load the js file before . This will not affect the loading speed of the web page. If it is placed in the head, it will Load the js file first.


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