We can place JavaScript code anywhere in the html file, but we usually place it in the head or body part of the web page.
Put it in the <head> part
The most common way is to place the <script> element in the head part of the page. The browser will execute this code when parsing the head part, and then parse the rest of the page.
Place it in the <body> section
The JavaScript code will be executed when the web page reads this statement.
The following code:
<!DOCTYPE html> <html> <head> <title>javascript</title> <script type="text/javascript"></script> </head> <body> </body> </html>
In this way, our js code is placed in the head tag
It can also be placed in the body, as shown below
<!DOCTYPE html> <html> <head> <title>javascript</title> </head> <body> <script type="text/javascript"> </script> </body> </html>
Note : JavaScript as a scripting language can be placed anywhere in the HTML page, but when the browser interprets the HTML, it is in order, so the previous script will be executed first. For example, the js for page display initialization must be placed in the head, because the initialization must be done in advance (such as setting css for the page body, etc.); and if the function is executed through an event call, there is no requirement for the location.
Let’s take a look at the format of js code
<script type="text/javascript">
At the end of each js statement, a semicolon in English must be written. Although it does not need to be written, we still write it in order to standardize the writing of the code. Next, we will write an example:
<!DOCTYPE html> <html> <head> <title>javascript</title> </head> <body> <script type="text/javascript"> document.write("HELLO "); document.write("WORLD"); </script> </body> </html>
Note: document.write is the output statement, we will talk about it later
Next Section