When we want to use Javascript we have two options to include it in our web page, the first one is to put directly the code between the <head>
and </head>
tags and the second one is to use an external file with extension .js. In this post we will talk about how to create this .js file.
The external file has the advantage of making your page lighter because it is saved in the browser cache and does not have to be loaded on each visit. The creation of this .js file can be done in several different ways:
1. With a program for creating and editing code, also known as IDE (Integrated development environment) it is very easy to create it. I recommend using a free program, but also libre, like KDevelop, available for Windows, GNU/Linux and macOS. In KDevelop you just need to create a file (File / New), write your code and save it with .js extension (File / Save as).
2. With notepad. If for any reason you don’t have a web design software, you can create it with any note application.
- Open notepad.
- Paste your functions in the new document. In this file you should not include the
<script type="text/javascript"></script>
tags as when you include them directly in the HTML code, if they do appear in your function, just remove them. - Go to the “file” menu and “save as”. In the file name, delete the default name and write the name of your file but with ending “.js”, for example: functions.js.
A little below, in the “Type” tab select “All files” and below this, in the “encoding” tab select “UTF-8” and that’s it, you have your .js file, upload it to your host or to a free host like neocities.
To link it, we go to the HTML code of our page and we place ourselves between the tags <head>
and </head>
. It is here where we will make the call to the file and we will do it in the following way:
<script src="functions.js" type="text/javascript"></script>
Where we only need to change the location of our script, i.e. replacing functions.js with the full URL to the location of our JS file.
I hope you find it useful, it is very basic, but it is always difficult when you don’t know it.