tonga
tonga

Reputation: 11981

Is a JavaScript function defined in <script> block accessible by another JS function?

I have the following code in my HTML file:

<script src = "js/create.js"></script>
<script>
    function show() {
              //some code here
    }
</script>

In the JavaScript file create.js, I want to call the function show() defined in the block, like this:

//File create.js
var a = show();

So is the function show() accessible in the file create.js?

Upvotes: 2

Views: 8015

Answers (3)

ASertacAkkaya
ASertacAkkaya

Reputation: 661

You could have just tried this one out, but I'll still try to briefly explain.

Since JavaScript is client side, it depends on the current state of the client side. Until the needed part is loaded, you won't be able to access it.

In your case, you first include your create.js file. When it is loaded, the next one isn't yet. So var a = show(); will look for the function named show(); however will throw an error saying null reference to the function, as it wouldn't be available in client yet.

The way you can avoid this is to check whether the parts of the documents were loaded. In jQuery, this is made with $(document).ready, in classic JavaScript you can somewhat depend on window.onload, body tag's onload.

There is also another casual way of doing this, see the following sheet.

<html>
 <head>
  <title>Test!</title>
  <script type="text/javascript">
  function show(){
      alert("Hey there!");
  }
  </script>
 </head>
 <body>
  <h1>Hey there!</h1>
  <p>The alert box should appear after these lines are loaded in client, this will also mean the head is completed, so it's safe to call the function show()</p>
  <script type="text/javascript">
      show();
  </script>
 </body>
</html>

In that, we can certainly assume the function defined in the head was loaded until the point the second script, which calls the defined function can be runnable safely.

Upvotes: 3

DOK
DOK

Reputation: 32851

Yes, this is how add-in libraries like jQuery work. You include their .js file, and then call its methods.

Upvotes: 1

bbs
bbs

Reputation: 2022

Yes, you defined the function without putting it in a var so it will be hoisted to the most outer scope being the global scope. But you run create before that function is declared so it wont see it, turn them around and see.

Upvotes: 5

Related Questions