Pages

Monday, 23 April 2012

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

  • Security and Privacy- Competitors and Hackers cannot see the code. The external file can be blocked from public view.
  • Reusability- The same code can be used on multiple pages and
  • Easy Updating- In case of updating the JS code, it has to be done only in the external file instead of all the individual pages.

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
prev<<Using Javascript in HTML documents

No comments:

Post a Comment

Thank you for your valuable comment