0

My question:

I have 2 files:

//Sub.js
function Second() {
    //do something here
}

//Main.js
function One() {
    //do something here
}
$(function() {
    Second();
});

So basically, the function Second is too long; therefore, I want to move it to a Sub.js file and call it from the Main.js. The problem is this function ( function Second) has to be executed after function One because it gets some data from the function One output.

I don't know how to do this, please help.

2
  • 1
    This may be of assistance stackoverflow.com/questions/41268431/…. Commented Sep 19, 2017 at 5:50
  • There is only function declaration in main.js, where are you invoking the method one()? Commented Sep 19, 2017 at 5:50

4 Answers 4

2

If you specifically want to use jQuery,

$.getscript("Sub.js",function(){
   Second();
});
Sign up to request clarification or add additional context in comments.

Comments

0
<script src="/lib/Sub.js"></script>

<script src="/main.js"></script>

I think you should initialize firstly Sub.js before main.js in your head code.

Because whenever the page is first load js are intialize one by one.

Comments

0

You can include both the files in the page and on document ready call it sequentially:

    $( document ).ready(function() {
        var result = first();
        second(result);
    });

Comments

0

I was getting a similar problem. My solution was this. I was defining my function inside the .ready() callback. But The problem is that the functions is not accessible outside of its scope. To make this function available in the global scope (or through any object that is available in the global scope) is necessary declare outside the .ready() callback:

Wrong Way:

$(document).ready(function() {
    function functionName () {
        // ...
    }

    // ...
});

Right Way:

function functionName () {
    // ...
}

$(document).ready(function() {
    // ...
});

Comments

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.