4

There is an external js which I call in to the main page. This external file has a function

function fruitLib(){
   //do stuff
}

I have another external js and there is another function.

function price(){
   //do stuff
}

Now how can I check if fruitLib() exists before calling price()? Below is what I tried but doesn't work (maybe because both files are external files).

if (typeof fruitLib== 'function') { 
  price(); 
}
Becky
  • 5,467
  • 9
  • 40
  • 73
  • Your check is fine if `fruitLib` is a global function. Can you provide more information? – T.J. Crowder Nov 30 '15 at 10:53
  • @T.J.Crowder Thanks for your reply. None of them are global functions. I just have `functionA` in `one.js` and I want to call `function` of `two.js` only if `functionA` is available. – Becky Nov 30 '15 at 10:56
  • For it to be available, it must either be a global function or a value you receive as the result of a function call (for instance, using some kind of AMD). – T.J. Crowder Nov 30 '15 at 10:57
  • Thanks. If `price()` is in the main html file, is it possible to check if `fruitLib()` is available? – Becky Nov 30 '15 at 11:00
  • As I said: The check you have will work. It will work if `fruitLib` is a global, and it will work if `fruitLib` is a variable you've received a function reference into. The question makes no sense at present. – T.J. Crowder Nov 30 '15 at 11:09
  • @T.J.Crowder Thanks. So `$.ab.fruitLib= function(){` would be the solution? – Becky Nov 30 '15 at 11:15
  • @T.J.Crowder Also in according to [this](http://stackoverflow.com/questions/1042138/javascript-check-if-function-exists/) `if (typeof $.ab.fruitLib=== "function") { ` would be the safer solution. Any comments on that?. – Becky Nov 30 '15 at 11:18

1 Answers1

2

Assuming that fruitLib() is in file foo.js and price() in bar.js, do this in the area that you include your JavaScript files:

<script src="foo.js">
<script src="bar.js">

That way you know that fruitLib() is loaded before price().


A relevant question lies here: Javascript check if function exists.

Community
  • 1
  • 1
gsamaras
  • 71,951
  • 46
  • 188
  • 305
  • Thanks. Is it possible to check if`fruitLib()` is available, if `price()` is in the main html itself? – Becky Nov 30 '15 at 11:02
  • Becky you are welcome, it's a nice question, that's why I am upvoting! Well doesn't the link helps? I have a class now. If you still have issues let me know. – gsamaras Nov 30 '15 at 11:04