1

So two part question here. Basically, what is the proper practise for javascript function locations? I assumed it would be to have several MyScriptFile.js files, each with a few functions instead of one huge AllMyScripts.js file, as not every page needs every function.

However I'm not sure how to reference another function from outside of this file...

My situation: I'm using an AJAX request in many of my pages. Each request response is different (drawn from different files, etc) and is very hard to make dynamic (one-script-fits-all would be difficult). However, I do have my MakeAJAXRequest() function which creates the request object, which is standard to all DoSomethingWithRequest() functions.

How do I include MakeAJAXRequest() in the other files which contain the DoSomethingWithRequest() functions? It seems as though I should have been able to find this.. but I havn't come across it.

tl;dr I have MakeObject.js and UseObject.js. How does UseObject() reference MakeObject()?

EDIT: Found that if you include MakeObject BEFORE UseObject in your HTML <script> tags, UseObject will be able to reference MakeObject. Seems a little dirty still, as anybody who wants to use the UseObject script will have to be aware of the MakeObject dependency...

StuckAtWork
  • 1,613
  • 7
  • 23
  • 37
  • 1
    Check thsi out : http://stackoverflow.com/questions/950087/include-javascript-file-inside-javascript-file – eric.itzhak Jun 15 '12 at 17:43
  • I had seen that article, but it seemed a little intensive for a simple include. These .js files have nothing but functions in them. Is it really not possible to do something along the lines of `newObject = /myDir/mySubDir/MakeObject.js.MakeObject()`? – StuckAtWork Jun 15 '12 at 17:44

1 Answers1

0

If you want to ensure your dependencies are loaded, you could use a function such as this: http://phpjs.org/functions/include:433 There is also include_once(), require(), and require_once()

solidau
  • 4,021
  • 3
  • 24
  • 45
  • Wouldn't that mean I'm then loading an extra function, in order to include my function? – StuckAtWork Jun 15 '12 at 18:13
  • yah, but you'd only have to include one file on the HTML page, and then chain the rest off that. so you don't have to remember to include your dependencies. is that not what you wanted? "How do I include MakeAJAXRequest() in the other files which contain the DoSomethingWithRequest() functions?" this is how, and you will do the same with this dependency. – solidau Jun 15 '12 at 18:42
  • I'll give it a try. It will solve the problem of anybody else needing to perform the include, but it doesn't really save on file size (actually there's more code to do an include than to simply copy/paste the MakeAJAXRequest() script), but the principal is right and therefor I can make a change only to MakeAJAXRequest.js and have it propagate (which was the main intention). Thanks! – StuckAtWork Jun 15 '12 at 18:57