When a page is loaded, Javascript in the body is executed.
When called, the JavaScript code in the head part is executed.
Instance
-
Head Section
-
The script containing the function is located in the head part of the document. In this way, we can ensure that the script has been loaded before calling the function.
-
Body section
-
Execute the script in the body part.
-
External Javascript
-
How to access external scripts.
Where to place Javascript
The script on the page will be executed immediately after the page is loaded into the browser. We don't always want this. Sometimes, we want to execute the script when the page is loaded, and in other cases, we want the script to be executed only when the user triggers the event.
Scripts in the head section:
When a script is called or an event is triggered, the script is executed. After you place the script in the head part, you can ensure that it has been loaded before you need to use the script.
<script type="text/javascript">....</script>Scripts in the body section:
The script is executed when the page is loaded. After you place the script in the body, it will generate the page content.
<script type="text/javascript">....</script></body>Scripts in the body and head sections:
You can place any number of scripts in the document, so you can place the script both to the body and to the head part.
<script type="text/javascript">....</script><script type="text/javascript">....</script></body>Use external Javascript
Sometimes, you may want to run JavaScript on several pages and not write the same script on each page.
To achieve this, you can write Javascript into an external file. Save the file with the suffix. js.
Note: external files cannot contain <SCRIPT> tags.
Then, specify the. js file to the "src" attribute in the <SCRIPT> tag to use this external file:
<script src="xxx.js">....</script>
Tip: You can put the. js file in the subdirectory where the script is usually stored in the website directory, which is easier to manage and maintain.