External Files
Lesson 4Author : Afrixi
Last Updated : March, 2023
When we have a lot of JavaScript code, it’s best to put it into a separate file and attach it to our HTML page using the src attribute of the <script>
tag.
To do this, we need to specify the path to the script file, either as an absolute path from the site root or a relative path from the current page. For example, if our script file is located in the same folder as our HTML file, we can use src=“script.js” or src="./script.js".
We can also specify a full URL to the script file, such as src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"
.
If we need to attach multiple script files, we can use multiple <script>
tags with the src attribute. For example:
<script src="/js/script1.js"></script>
<script src="/js/script2.js"></script>
By putting our JavaScript code into a separate file and attaching it to our HTML page with the src attribute, the browser can download and cache the file, making our pages faster to load and reducing traffic.