Thursday, 13 March 2014

EXTERNAL JAVASCRIPT FILES




External JavaScript Files:

Javascript code can also be placed in an external file. Your SCRIPT tags then include a SRC attribute that points to the location of your Javascript file. Here's the HTML:


<HEAD>
            <TITLE>A First Script</TITLE>
            <SCRIPT LANGUAGE=”JavaScript” src=”scripts/external_javascript.js”>
</SCRIPT>
</HEAD>
In the code above, we have added the following attribute to the opening SCRIPT tag:
SRC="scripts/external_javascript.js"
SRC stands for Source. After an equal sign, you type the path to your Javascript file. We created a folder called scripts. Inside of this folder we placed a file called external_javascript.js.
Note the new extension - js. When saving code in an external file, end the file name with the two letter extension js.

The file itself is this:
External_javascript.js
alert (“External JavaScript file”)

All we have here is the alert box line. Notice that we don't need any SCRIPT tags in the external file. That's because they are already included in the HTML code. When the browser parsers the HTML it sees the SRC attribute and then includes all your Javascript at that point.
When your code gets too long and unwieldy, placing it in an external file helps you to control it more. Plus, if you need to make changes to the Javascript you'll only need to amend one file, instead of making changes to the HEAD section of lots of HTML files.

No comments: