Home > Article > Web Front-end > Where should JavaScript code be placed in HTML code? _javascript skills
Where to place JavaScript code?
Normally, JavaScript code is used together with HTML code, and JavaScript code can be placed anywhere in the HTML document. However, where it is placed will have a certain impact on the normal execution of JavaScript code, as detailed below.
placed between
It is a common practice to place JavaScript code between the
tags of an HTML document. Since HTML documents are loaded by the browser from top to bottom, placing JavaScript code between the tags ensures that it has been loaded before the script needs to be used:placed between
There are also some cases where JavaScript code is placed between
. Imagine the following situation: we have a piece of JavaScript code that needs to operate on HTML elements. However, since the HTML document is loaded sequentially from top to bottom by the browser, in order to prevent the JavaScript code from operating the HTML element and reporting an error (the object does not exist) before the HTML element is loaded, this code needs to be written to the HTML element. Later, the example is as follows:But usually, our operations on page elements are generally driven by events, so the above situation is rare. In addition, we do not recommend writing JavaScript code outside of .
Tips
If the HTML document is declared as XHTML, the <script></script> tag must be declared within the CDATA section, otherwise XHTML will parse the <script></script> tag into another XML tag inside JavaScript code may not execute properly. Therefore, JavaScript used in strict XHTML should be declared like the following example:
External reference JavaScript code
Form the JavaScript code (excluding the<script></script> tag) into a separate document, name it with a js suffix, such as myscript.js, and place it in the HTML document<script></script> tag Use the src attribute to reference the file:
After using externally referenced JavaScript code, the benefits are obvious:
1. Avoid using
in JavaScript code
2. Avoid using ugly CDATA
3. Public JavaScript code can be reused in other HTML documents, which also facilitates the unified maintenance of JavaScript code
4.HTML documents are smaller, which is easier for search engines to include
5. Can compress and encrypt a single JavaScript file
6. The browser can cache JavaScript files to reduce bandwidth usage (when multiple pages use a JavaScript file at the same time, it usually only needs to be downloaded once)
7. Avoid using complex HTML entities. For example, you can use document.write(2>1) directly without writing document.write(2<1)
Forming JavaScript code into external files will also increase the HTTP request burden on the server. This is not a good strategy in an environment with ultra-high concurrent requests. In addition, when referencing external js files, you need to pay attention to the correct path of the file.