PageResource.com - Web Development Tutorials

Using an External JavaScript

How to make one javascript work on multiple pages

Have you been looking for a way to use one page of javascript code on multiple pages, without needing to paste the code into page after page? Well, this is where an external javascript can help! You can call functions from an external javascript on any page that you put the special <SCRIPT></SCRIPT> tags on.

So, what do these special tags look like? They look like a plain script tag, but they use an extra attribute: The SRC="http://someplace.com/script_name.js" attribute.

Here is an example of one of these tags:

<SCRIPT language="JavaScript" SRC="http://www.pageresource.com/jscript/jxt1.js"></SCRIPT>

The SRC attribute names a source for the javascript to be used. The script must be saved with the extension .js as a plain text file.

So, let's give it a try. Open a new document in your text editor, and write the following code into it:

function a_message()
{
alert('I came from an external script! Ha, Ha, Ha!!!!');
}

Now, save the file as "jxt1.js".

You can now use this script on any page you place the special script tags on. Place the script tags inside your <HEAD></HEAD> tags. Be sure the SRC attribute points to your .js file. If you are working in one directory, just use the tag this way:

<SCRIPT language="JavaScript" SRC="jxt1.js"></SCRIPT>

If not, try an absolute url. Be sure to change this to your domain and the correct directory:

<SCRIPT language="JavaScript" SRC="http://someplace.com/jxt1.js"></SCRIPT>

Now, you can call your message function from the page that you placed the tags on. I will use a link as an example:

<A HREF="javascript:a_message()">Click for a message..</A>

I used the same script for this example, clicking on the link will bring up our message from the external script. (If you are not familiar with this kind of link tag, see the JS link tutorial for details.

Click for a message..

This script is not very useful, it will just give you one alert message to use on every page (Yuck!). However, it shows you how to call a function from an external script (just like a normal function). I'm sure you can think of some better scripts to use with this. (Actually, I can too, but I'm too lazy to type out a long script here...).

This is a handy way to use one script on multiple pages. By adding the script tags to each page you need the script on, you can reuse a script over and over without typing the entire script on every page. Now, get out there and find some more useful scripts to use for your own external javascripts!

Well, that does it for now. Let's go on to The Date Object: JS Clock.

previous
Previous
By: John Pollock next
Next

Copyright © The Web Design Resource. All rights reserved. | Contact Us | Privacy Policy