The location of the javascript code: 1. Place it in the "
" tag pair to ensure that the js code has been loaded before the script needs to be used; 2. Place it in "" tag is centered; 3. Place it in an external file of ".js" and introduce it with the script tag.
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
Where to put 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.
Place between
Place the JavaScript code between the
tags of the HTML document time is a common practice. 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:<html> <head> <script type="text/javascript"> …… JavaScript 代码 …… </script> </head> ....
Placed between
There are also some cases where JavaScript code is placed between
of. 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:<html> <head> </head> <body> </body> <div id="div1"></div> <script type="text/javascript"> document.getElementById("div1").innerHTML="测试文字"; </script> </html>
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 .
Tip
If the HTML document is declared as XHTML, the <script></script> tag must be declared within the CDATA section, otherwise XHTML will convert