When you write JavaScript, you should write them in a JavaScript file that ends with a .js extension. Doing so allows you to use the same set of JavaScript code across all your HTML files.
These JavaScript files can be named anything you want. Most people name their first JavaScript file either app.js or main.js.
These files are then stored in a js folder that’s located at the same level of your HTML files for easy identification.
Linking your JavaScript file to your HTML file.
For your JavaScript files to work, you need to link them to your HTML. You do so by adding a <script> tag at the bottom of your HTML, before closing the </body> tag.
This <script> tag should contain a src attribute that points to your JavaScript file, like this:
If you do this, the browser cannot begin displaying your HTML and CSS until it has finished downloading your JavaScript. It delays your users from viewing your content.
If you want to add your JavaScript file at the top of your HTML, make sure to use the async attribute which tells browsers to download the file only after it’s done with other tasks.
<head>
<title>Title of website</title>
<!-- The async attribute is important if you put your JavaScript in the head -->
<script src="js/main.js" async></script>
</head>
Relative and absolute paths
In the examples above, you linked your JavaScript file with a relative path. They begin directly with the name or folder of the file you’re trying to link. This code below tells browsers to look into the js folder that is for the main.js file.
<!-- Example of relative url -->
<script src="js/main.js"></script>
Absolute paths, on the other hand, begin with a / or a HTTP protocol:
<!-- Examples of absolute url -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="/js/main.js"></script>
In general, you should link your JavaScript files with relative URLs unless you need to link to an external resource like jQuery shown in the example above.
Exercise
Create a folder on your computer for going through this course. In this project folder, create a HTML file and a JavaScript file. Link your JavaScript file to your HTML file.