1

I tried this in my code :

<head>
    <meta charset="utf-8">
    <script type="text/javascript" src = "a.js"></script>
    <script type="text/javascript" src = "b.js"></script>
</head>

a.js contains

console.log("a.js");
show();

b.js contains

console.log("b.js");

function show() {

    console.log("function show()");
};

However the console shows error :Uncaught ReferenceError: show is not defined

As I combine a.js and b.js into one, it works OK.

So why is this happening when I have multiple source files? I thought it was the same as one single file with the content of both.

Besides, are there something else I should notice when I use multiple js sources?

Johnny Chen
  • 1,925
  • 1
  • 15
  • 26

4 Answers4

3

Try this:

<script type="text/javascript" src = "b.js"></script>
<script type="text/javascript" src = "a.js"></script>

This is because the function is defined in b.js. So, you have to call the function, which is in a.js, after b.js is loaded.

chris97ong
  • 6,267
  • 6
  • 28
  • 48
2

The problem is because your code runs when the script is ready/loaded, and that is when the <script> tag is processed. So it will load and run a.js before b.js has been loaded (and thus the function does not yet exist).

There are a few ways you can solve this, here are a couple:

1) You could reverse the order that you load the scripts:

<script type="text/javascript" src = "b.js"></script>
<script type="text/javascript" src = "a.js"></script>

2) You could add your code into a document ready event, which would wait for all scripts to be loaded before processing the code (uses JQuery):

$(document).ready(function(){
    console.log("a.js");
    show();
});

If you want a pure javascript method (no JQuery) then check this out (it's a bit too extensive for me to include as part of this answer)

Community
  • 1
  • 1
musefan
  • 45,726
  • 20
  • 123
  • 171
1

The order of including the js files is important.

When different JS is included in the html page the browser reads it in that same order.

So the function show is not yet defined for the browser when it's called in a.js

Simply include b.js before a.js

loxxy
  • 12,505
  • 2
  • 21
  • 52
1

as soon as a.js is loaded it will execute the show(); statement, up till this point function show is not defined because b.js is not loaded

reversing the order of the files means that by the time show(); statement is executed function show() is already defined

when you combine the two js files (does not matter in which order they are combined in your case) and link to that js file the script when loaded contains the definition for function show(), and the show(); statement does not throw an exception

user2321864
  • 1,839
  • 5
  • 24
  • 31