coding180 icon
Coding180
Reference JavaScript as external file

Reference JavaScript as external file

Home > Tutorials > JavaScript > Getting Started


In the previous lesson, we leaned to use the <script> tag to add JavaScript code in the HTML file, as shown in the figure:

javascript internal html

Can JavaScript codes only be written in HTML files? Of course not, we can separate HTML files from JS codes, and create a separate JavaScript file (JS file for short), whose file suffix is ​​usually .js, and then write the JS code directly in the JS file.

HTML File:

<html>

<head>
</head>

<body>
</body>

</html>

JavaScript File:

 <script type="text/Javascript">
        alert("Hello Coders!");
    </script>

 

Note: In the JS file, there is no need for the <script> tag, just write the JavaScript code directly.

The JS file cannot be run directly, it needs to be embedded into the HTML file for execution, we need to add the following code in the HTML to embed the JS file into the HTML file.

<script src="script.js"></script>

 

Complete HTML File:

<html>

<head>
    <script src="script.js"></script>
</head>

<body>
</body>

</html>

Complete JavaScript File:

alert("Hello Coders!");

 

Task - Exercise 3

line 6 of the code below uses:

<script src="script.js"></script> 

to make references to script.js file.

Now create the script.js file with the content below: 

document.write("Reference the JS file!"); 

Now run the code to see the result.

Task Code

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Reference JS file - colding180</title>
<script src="script.js"></script>
</head>
<body>
</body>
</html>

 


user

Robort Gabriel

Lagos, Nigeria

Freelance Web Developer, Native Android Developer, and Coding Tutor.

Skills
  • UI / UX
  • JavaScript
  • Python
  • PHP
  • Kotlin
  • Java
  • Bootrap
  • Android
  • Laravel