Content Menu

Home-What is JavaScript?

JavaScript tutorials

1. JavaScript Basics

2. JS Simple Coding

3. JS InterActive Content

4. Images and JS

5. JS Functions

6. JavaScript Events

7. JS Conditional

8. JS Loops

9. Other

JavaScript in External file. Link JS to HTML

As noted in the previous lesson, Javascript can also be put into an external file and the Html page that we wish to use the Javascript code on, is linked to that external file.

It works in a similar way as CSS code is put in External Style sheets.

Advantages of placing Javascript code in External File

How to link the Javascript and Html files?

STEP 1- Create JavaScript external file

Create a new file, write in the Javascript code and SAVE AS it with .JS extension.

javascript external file

The external file will just contain the javascript code and not the html <script> </script> tags.

js code external

STEP 2- Link html to Javascript File

Use the Script tags, however instead writing in the code specify the location of the file that contains the code. Path of the file is defined with 'src'
In the example below the JS file was in the same folder as the html file. If folders are different, appropriate path needs to be defined.

<html>
<head>
<title> JavaScript in external file</title>

<script type="text/javascript" src=sample.js>

</script>
</head>

<body>

</body>
</html>



STEP 3- Load the html file which will call Javascript

Open the html file in a browser.

Result.
javascript html link result

NEXT- JS Variables