babadahal
babadahal

Reputation: 41

Not able to call function from another .js file in (document).ready()

I have 2 files.

main.js utils.js

main.js

$(document).ready( function() {
    function instantiate_point_clouds(viewer_settings, cloud_meta) {
    }
})

utils.js

$(document).ready( function() {

    instantiate_point_clouds(viewer_settings, cloud_meta) ---> This is 
    Uncaught ReferenceError: instantiate_point_clouds is not defined
})

This is how I'm calling these js files.

<html>
  <head>
     <script src='/js/main.js'>
  </head>
  <body>
     <script src='/js/utils.js'>
  <body>
</html>

The function instantiate_point_clouds perfroms asynchronous calls, regardless shouldn't this be working as I'm calling main.js before my util.js. The function exists in main.js but says not defined if called from utils.js, does this have to do with $(document).ready() ?

Upvotes: 2

Views: 516

Answers (1)

Pablo Recalde
Pablo Recalde

Reputation: 3571

Define your function outside the

$(document).ready()

so it will get parsed on the page load and available to be used on $(document).ready()

As Isaac Abramowitz stated in the comments, when you define the function in your example code, you're doing it inside the scope of the anonymous function you're passing to $(document).ready() which the second call (no matter if its on the same file or not) can't reach as they don't share scope. More on this topic could be found here

Btw, you can just use $(function(){}) instead of $(document).ready().

Upvotes: 2

Related Questions