JavaScript code can be included anywhere in an HTML document. But there are also the best ways to include JavaScript in HTML files.
- In the
- In the <body>...</body> section.
- In the <body>...</body> and
- Scripts and external files, then included in the
In the following sections, we'll see how different JavaScript approaches can be included:
If you want to run a script on some events, when the user clicks somewhere, such as, then the script should be the head, as follows:
This will produce the following results:
JavaScript in <body> </body> part:
If you need a script to load the page so that the script generates page content to run, the script is in the <body> part of the document. In this case, you do not have to use all of the features defined by javascript:
JavaScript in the <body> and
You can put the JavaScript code in the
In JavaScript external files:
When you start working and use JavaScript more extensively, you may find that there are cases where you reuse the same JavaScript code on multiple pages in your site.
You are not limited to the same code that will remain in multiple HTML files. The script tag provides a mechanism that allows you to store JavaScript in an external file and then include it in an HTML file.
Here is an example of how to use script tags and SRC attributes to include external JavaScript files in HTML code:
Using JavaScript from an external file source, you need to use extensions to write down all the JavaScript code in a simple text file ". js", and then include the file as shown in the figure above.
For example, you can keep the contents of the following file Filename.js, and then include the Filename.js file and use Sayhellofunction in the HTML file:
function SayHello () {
alert ("Hello World")
}