Calling a JavaScript function in another js file

Solution 1:

A function cannot be called unless it was defined in the same file or one loaded before the attempt to call it.

A function cannot be called unless it is in the same or greater scope then the one trying to call it.

You declare function fn1 in first.js, and then in second you can just have fn1();

1.js:

function fn1 () {
    alert();
}

2.js:

fn1();

index.html :

<script type="text/javascript" src="1.js"></script>
<script type="text/javascript" src="2.js"></script>

Solution 2:

1st JS:

function fn(){
   alert("Hello! Uncle Namaste...Chalo Kaaam ki Baat p Aate h...");
}

2nd JS:

$.getscript("url or name of 1st Js File",function(){
fn();
});

Solution 3:

You can make the function a global variable in first.js and have a look at closure and do not put it in document.ready put it outside

you can use ajax too

    $.ajax({
      url: "url to script",
      dataType: "script",
      success: success
    });

same way you can use jquery getScript

$.getScript( "ajax/test.js" )
  .done(function( script, textStatus ) {
    console.log( textStatus );
  })
  .fail(function( jqxhr, settings, exception ) {
    $( "div.log" ).text( "Triggered ajaxError handler." );
});