JavaScript is used in the page, so where should these JS codes be placed? Let’s take a look.
Generally speaking, there are two ways, writing on the interface and using .js files.
Head part on the 1.1 interface
can be placed directly in the head tag, as shown below
<html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>testPage</title> <script type="text/javascript"> //your js code </script> </head> <body> <form id="form1" runat="server"> <div> </div> </form> </body> </html>
The body part on the 1.2 interface
It is usually placed directly in the body part, as follows
<html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>testPage</title> </head> <body> <form id="form1" runat="server"> <div> </div> </form> <script type="text/javascript"> //your js code </script> </body> </html>
There is no difference between placing it in the head and body. Generally, when the amount of code is not large and only the current page uses these js, then write it directly on the interface.
2. JS file
For those JS that are complex and have a lot of code, it is best to put them in a special .js file, and then reference them on the page according to the relative path of the js file.
The advantage of this is that it can prevent a lot of duplicate js code. Some public js methods can be placed in external js files.
For example, the jquery-1.4.1.js file is usually included in asp.net projects created using visual studio 2010. Let’s see how to use this js file.
For example, the file structure of the page is as shown in the figure,
To use this js file in MyJSFrm.aspx, import it like this.
<html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>testPage</title> </head> <body> <form id="form1" runat="server"> <div> </div> </form> <script type="text/javascript" src="/Scripts/jquery-1.4.1.js"></script> <script type="text/javascript"> //your js code </script> </body> </html>
In short, don’t forget to use relative directories. If the directory level of the current page file is relatively deep, then use ../ to calculate the directory level yourself.
The difference between the three positions of js:
head :
-- When calling the script, loading has been completed
--
body:
-- Loading has been completed when the page is generated
--
External js:
--Refer to external js Note: External js cannot contain the two tags <script></script>
-- Mainly to save the need to embed the same js code in each page when multiple pages repeatedly call the same js function;
The browser does not recognize js solution: