0

I have two JS files. One is called common.js and it use $.getScript to include other file with my js code. Part of including looks like this:

jQuery.getScript(js_path + "table.js", function(){
  generateTable(chartData, dataTypes);
});

This file (common.js) also contains function compare(a, b).

Now, the second one (table.js) has declared different function which uses the compare function from the first file. Something like this:

function someName() {
  var a = 2, 
      b = 5;
  var test = compare(a, b);
  return test;
}

When I run the code it gives me:

Uncaught ReferenceError: compare is not defined

How can I use function from the first file.

fmsf
  • 36,317
  • 49
  • 147
  • 195
David
  • 1,932
  • 3
  • 27
  • 35
  • here the example [take a look](http://stackoverflow.com/a/3809896/2749470) – Bhargav Modi Feb 13 '15 at 12:17
  • Is there a particular reason that you need to use the getScript rather than simply including both scripts? – Luc Feb 13 '15 at 12:19
  • @Luc I have to divide the code into separate files to make it more clear – David Feb 13 '15 at 12:21
  • @David Yea, but you can put multiple script-tags rather than fetching one with the other. Beside that point, you clearly have a circular dependency between the two files which makes it a bit tricky. – Luc Feb 13 '15 at 12:26
  • right, but there are dependencies between them so that's why I have to use it – David Feb 13 '15 at 12:29

3 Answers3

0

jQuery.getScript first fetches the JS file from the server, then executes it. If you want to work with global functions (as it seems) you need to pay attention to the following:

  • Your compare function must be declared before the table.js file is executed.

  • The compare function must be declared on the global namespace of table.js.

Sorry but without more info this is all you can get.

If your main file, as something like:

(function() {

   function compare(){...}

}());

Then the compare function is not declared in the global namespace.

fmsf
  • 36,317
  • 49
  • 147
  • 195
-1

did you check the order of imports? The file with 'compare' method should be first. It should solve the problem.

  • this compare function is declared in the same file which uses getScript, but before getScript function is used – David Feb 13 '15 at 12:26
-1

What I would suggest is to skip getScript if it's just for separating the code.

<script src="common.js"></script>
<script src="table.js"></script>
<script src="app.js"></script>

Where common functions go into common, your table stuff goes into table. This way you get the ordering right. This also clears out the circular dependency one might see a hint of if table depends on common that depends on table by extracting all but the 'common' parts into some form of 'app'.

Luc
  • 273
  • 1
  • 9