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(); 
}
7
  • Your check is fine if fruitLib is a global function. Can you provide more information? Commented Nov 30, 2015 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. Commented Nov 30, 2015 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). Commented Nov 30, 2015 at 10:57
  • Thanks. If price() is in the main html file, is it possible to check if fruitLib() is available? Commented Nov 30, 2015 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. Commented Nov 30, 2015 at 11:09

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. Is it possible to check iffruitLib() is available, if price() is in the main html itself?
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.