You Are Here: Home »Tutorials»Html_js »   External js files Friday September 3rd 2010

External .js Files

Introduction

If you look at the source of other websites, for many you wont see any code inside the <script></script> tags and the reason for this is usually that they have all of their javascript code and functions inside a seperate file, a .js file.

This is useful if you have lots of different scripts or functions to add to your page, it means you don't have it all in the way when you want to edit your main page, your visitors browser will only need to download the file once rather than fetching the code each time if it was used directly in your pages making things quicker for them, you can also include as many different scripts as you like in one file.

Basically, anything that you would normally put inside your <script></script> tags can go into a .js file.

Creating The File

Open up notepad or whatever text editor you use, don't add any html or body tags or anything like that, just paste in the code from inside your script tags.

You must remove the <script></script> tags themselves and put the code only into the .js file, the tags are used in your page to tell the browser that what's inbetween is to be read as Javascript, well everything inside a .js file is automatically read as javascript so we don't need the tags (it wont work if they are there) example, if you had this in your page:

<script type="text/javascript">
<!--
function myfunction() {
                do something
}
//-->
</script>

And you wanted to transfer that to a .js file, you would just use:

function myfunction() {
                do something
}

Now save the file as anything.js and make sure your text editor doesn't add another extension like .txt or .htm to the end it needs to be "filename.js" exactly (without the quotes).

Including The File

Upload it to your webspace and use the following to 'call' the file inside your <head></head> tags:

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

That's all, and if you uploaded the .js file to a directory make sure you use the correct path e.g src="path_to/filename.js"