leora
leora

Reputation: 196891

can i call one js file from another .

i have an asp.net mvc app and i am trying to move all of my javascript out into js files. right now i have one called sharedfunctions.js which is used all over the place.

the issue is that if i move some code into a js file that is calling a method in the sharedfunctions.js file, it no longer seems to work.

what is the best way to be able to factor out common code among js files and allow them to actually work properly ?

Upvotes: 5

Views: 8587

Answers (5)

Justin Johnson
Justin Johnson

Reputation: 31300

Some library solutions

Dojo: dojo.require("my.package.name");

jQuery: $.getScript("url/to/script.js", function() { /* callback */ });

Upvotes: 0

Itay Moav -Malimovka
Itay Moav -Malimovka

Reputation: 53606

The best way is to have it all in one file, and on your development environment, where it is broken into file-per-class or what ever method you use, just include them in the correct order.

If you want to include a JS dynamically (using moo-tools short cuts, although you can simply use their assets library)

$$('head')[0].adopt(new Element('script',{'type':'text/javascript','src':'path to js file'}));

Upvotes: 0

Rob Levine
Rob Levine

Reputation: 41358

As long as all the .js files are referenced on the page inquestion, functions/variables in all them will be accessible by any others once the page has loaded.

I'm highlighting that last bit because it may well be the root cause of your problems. It may be that the order that the .js files are loading is wrong.

If you have some javascript that executes immediately (e.g. it is not triggered by a page event), then it may well start executing before your sharedfunctions.js file has been included on the page. In this case, the function in sharedfunctions.js literally won't exist at the time the other javascript executes.

See if you can look at the order of things to eliminate these problems. For example, try and ensure your sharedfunctions.js loads as the first script file on the page.

IMHO, this is preferable to trying to hack your existing js files to load the contents of other js files directly.

Upvotes: 5

Code Monkey
Code Monkey

Reputation: 421

Is the issue that you think your overwriting your functions with bogus ones? If thats the case before you define a function you can check to see if you already have it defined.

if(typeof yourFunctionName == 'function')

Upvotes: 1

alemjerus
alemjerus

Reputation: 8268

Use this pattern:

function IncludeJavaScript(jsFile)
{
  document.write('<script type="text/javascript" src="' + jsFile + '"></scr' + 'ipt>'); 
}

Upvotes: -1

Related Questions