Connecting an External JavaScript File

In the last article, the JavaScript code was directly defined on the web page. But there is another way to include JavaScript code, which is to take the code to external files and include them using the tag <script>

So, in the last topic, we created an html page index.html , which is located in the app directory . Now let’s create a new subdirectory in this directory. Let’s call it js . It will be designed to store files with JavaScript code. In this subdirectory, let’s create a new text file, which we’ll call script.js . JavaScript files have the .js extension . That is, we get the following project structure in the app folder.

Let’s open the script.js file in a text editor and define the following code in it:


document.write("<h2>First JavaScript program</h2>");
// display title
document.write("Hello world!");
// output plain text

Here, the method is used to add some content to the web page document.write. The first call to the method document.write prints the title <h2>, and the second call prints plain text.

For compatibility with the index.html page encoding, it is also desirable to set the utf-8 encoding for the JavaScript file. When working in Visual Studio Code, this editor automatically sets the encoding to UTF-8.

Now let’s include this file in the index.html web page :

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Connect Javascript External File</title>
    <script src="js/script.js"></script>
</head>

<body>

</body>

</html>

To include a JavaScript file on a web page, the <script> tag is also used, with the src attribute set . This attribute points to the path to the script file. In our case, a relative path is used. Since the web page is in the same folder as the js directory, we can write js/script.js as the path .

Also, keep in mind that the opening script tag must be followed by a closing one.</script>

And after opening the index.html file in the browser, a message will be displayed:

As opposed to defining JavaScript code, putting it in external files has a number of advantages:

We can reuse the same code across multiple web pages

The browser can cache external JavaScript files, due to this, the next time the page is accessed, the browser reduces the load on the server, and the browser needs to download a smaller amount of information

Web page code becomes “cleaner”. It contains only html markup, and the behavior code is stored in external files. As a result, you can separate the work of creating the html page code from writing the JavaScript code

Therefore, it is generally preferable to use JavaScript code in external files rather than directly pasted into a web page using a script element.