Import A JavaScript File
This is a small section compared to the others because it is focused only on how to import JavaScript files into your HTML coding.
There are 2 ways to use JavaScript in HTML, you either code your JavaScript within the HTML file or you create a JavaScript file separately and you import it into your HTML.
Let's take a look at both methods:
1. Inserting JavaScript
You can code JavaScript within your HTML files and your browser will be able to read it even with a ".html" format extension.
Writing any JavaScript code must be done within your "head" tag such as the example below:
<html> <head> <script type="text/javascript"> *** Your JS Starting tag. YOUR JAVASCRIPT CODE HERE *** Your JS Code Goes Here. </script> *** Your JS Ending Tag. </head> <body> YOUR WEBSITE CONTENT HERE </body> </html>
As you can see just by including the <script> tag you can write any JS code you want and your browser will be able to read it.
2. Importing JavaScript
Importing a JS file is very easy, the point is to create an external JS file and have all our JS code in it, then we import it into our HTML file.
This is a good idea since it makes the code look more cleaner and also allows us to choose which JS files to import in every page we want.
Let's take a look at this next example:
<html> <head> <script type="text/javascript" src="MyJSfile.js"></script> *** Use "src" to locate the file your JS is at, and you will be able to read the file as if it was coded inside of this HTML file. </head> <body> </body> </html>
You can see from the above that including a "src" attribute in the <script> tag, will allow us to enter a location for the JS file we wish to import into our HTML file.
