Forum Moderators: open

Message Too Old, No Replies

Putting javascript in an external file

A very basic question

         

kbish

8:38 am on Feb 20, 2005 (gmt 0)

10+ Year Member



I'm afraid I'm relatively new to javascript, but the few bits and pieces I'm using on sites I'd like to store in an external file, therefore avoiding having to cut and paste into various pages.

My question is how to put these scripts in the external file. Do I just add the various scripts one after the other, rather like styles in a CSS file, and the HTML pages will be able to call upon the relevant script/s as and when they're needed? Is it just as simple as that, or is there anything else I need to do, or are there any pitfalls I should be aware of?

This question is so basic that I haven't been able to find an answer to it anywhere I've searched! But when you're starting out you need to know, don't you?!

grandpa

9:54 am on Feb 20, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



I googled include javascript [google.com]

Create a new file with the extension .js.
Do not include opening and closing SCRIPT tags in the js file!
Include the javascript page in your html document like this:

<SCRIPT LANGUAGE="JavaScript" SRC="myscript.js"></SCRIPT>

Bernard Marx

9:55 pm on Feb 20, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



<script type="text/javaScript" src="myscript.js"></script>

are there any pitfalls I should be aware of?

Watch out for onload handler conflicts. There should be only one of these (if any):

window.onload = ...

<body onload="..">

kbish

2:21 pm on Feb 21, 2005 (gmt 0)

10+ Year Member



Thanks for those tips. But apart from that I can just list the various scripts one after the other in the file as you would styles in a CSS style sheet?

cunningmark

3:24 pm on Feb 21, 2005 (gmt 0)

10+ Year Member



If the scripts were working fine all in one page, then there should not be a problem just liting them in the .js file. (if there were not any conflicts before)

but if they came from different files, then you will need to name them (function) and call them as appropriate from the pages.