myFunction() function, which is called by clicking a button, being placed in the
myFunction() function, which is called upon a button click, is placed in the
Theory is great, but we recommend digging deeper!
<script> tag. Let's take a look.
<head> section, write a
<script> tag and add a
src attribute, setting it's value to the external file:
<script src="script.js"></script> <script src="moreScripts.js"></script>
Advantages of Such Usage
Placing scripts in external files has multiple advantages:
- It is easier to manage your code when it's split up among seperate files.
- If you're using the same scripts in different HTML files, including an external file prevents repetitive code.
As you already know, external HTML scripts can be linked to webpages using the
src attribute and setting its value to the external file's name:
/) is used to go up or out of the current folder into its parent folder.
The code snippet below indicates that the file
exampleScript.js is in a folder named js, which is located in the same folder alongside the HTML document.
Now take a look at the example below. This is how it would look if the script were located in the same folder as HTML file:
.jsfile. The path to it is included in the HTML file (placed within
<script>tag in the
- Placing your scripts in a separate
.jsfile and linking it to your HTML file is good practice.