PDA

View Full Version : Referencing external javascript file



kehers
Aug 17th, 2006, 01:08 PM
For reasons like reducing file size, organisation and having my function collection in a unit, i decide to put my javascript functions in an external js file (as against putting it inside the head tag) and reference the file using <script type="text/javascript" src="script.js" .....
The problem is that normal document objects that are easily accessible wen d script is inside d head tag arent accessible any more....
an example is that this:


var d = document.formname.elementname;

doesnt work. Got the error that looks something like that the object is null.
even this:


var d = document.forms[0].elements[0];

doesnt. Any ideas wat could be wrong?

Beagle
Aug 17th, 2006, 03:37 PM
Most likely, you are attempting to run that code before the document has fully loaded, which won't work. One solution is to include the script at the bottom of the page, so that all the HTML is loaded up first.

Bill Posters
Aug 17th, 2006, 03:59 PM
Another solution would be to keep the sourced js references in the head where they belong ( ;) ) and defer the running of functions using window.onload event.

e.g.

window.onload = doSomethingWithTheForm;

}

function doSomethingWithTheForm() {



}