207

Can we call the function written in one JS file in another JS file? Can anyone help me how to call the function from another JS file?

Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
Hemant Kumar
  • 4,593
  • 9
  • 56
  • 95

10 Answers10

227

The function could be called as if it was in the same JS File as long as the file containing the definition of the function has been loaded before the first use of the function.

I.e.

File1.js

function alertNumber(number) {
    alert(number);
}

File2.js

function alertOne() {
     alertNumber("one");
}

HTML

<head>
....
    <script src="File1.js" type="text/javascript"></script> 
    <script src="File2.js" type="text/javascript"></script> 
....
</head>
<body>
....
    <script type="text/javascript">
       alertOne();
    </script>
....
</body>

The other way won't work. As correctly pointed out by Stuart Wakefield. The other way will also work.

HTML

<head>
....
    <script src="File2.js" type="text/javascript"></script> 
    <script src="File1.js" type="text/javascript"></script> 
....
</head>
<body>
....
    <script type="text/javascript">
       alertOne();
    </script>
....
</body>

What will not work would be:

HTML

<head>
....
    <script src="File2.js" type="text/javascript"></script> 
    <script type="text/javascript">
       alertOne();
    </script>
    <script src="File1.js" type="text/javascript"></script> 
....
</head>
<body>
....
</body>

Although alertOne is defined when calling it, internally it uses a function that is still not defined (alertNumber).

Nick Suwyn
  • 501
  • 1
  • 5
  • 21
Edgar Hernandez
  • 4,020
  • 1
  • 24
  • 27
  • What is the different between your example by including JS file in Index.html file to the other approach where we use JS import method to import method from another JS file that has JS script method export to export method. – Phil Sep 17 '19 at 20:54
71

The answer above has an incorrect assumption that the order of inclusion of the files matter. As the alertNumber function is not called until the alertOne function is called. As long as both files are included by time alertOne is called the order of the files does not matter:

[HTML]

<script type="text/javascript" src="file1.js"></script>
<script type="text/javascript" src="file2.js"></script>
<script type="text/javascript">
    alertOne( );
</script>

[JS]

// File1.js
function alertNumber( n ) {
    alert( n );
};
// File2.js
function alertOne( ) {
    alertNumber( "one" );
};
// Inline
alertOne( ); // No errors

Or it can be ordered like the following:

[HTML]

<script type="text/javascript" src="file2.js"></script>
<script type="text/javascript" src="file1.js"></script>
<script type="text/javascript">
    alertOne( );
</script>

[JS]

// File2.js
function alertOne( ) {
    alertNumber( "one" );
};
// File1.js
function alertNumber( n ) {
    alert( n );
};
// Inline
alertOne( ); // No errors

But if you were to do this:

[HTML]

<script type="text/javascript" src="file2.js"></script>
<script type="text/javascript">
    alertOne( );
</script>
<script type="text/javascript" src="file1.js"></script>

[JS]

// File2.js
function alertOne( ) {
    alertNumber( "one" );
};
// Inline
alertOne( ); // Error: alertNumber is not defined
// File1.js
function alertNumber( n ) {
    alert( n );
};

It only matters about the variables and functions being available at the time of execution. When a function is defined it does not execute or resolve any of the variables declared within until that function is then subsequently called.

Inclusion of different script files is no different from the script being in that order within the same file, with the exception of deferred scripts:

<script type="text/javascript" src="myscript.js" defer="defer"></script>

then you need to be careful.

Stuart Wakefield
  • 6,294
  • 24
  • 35
  • 2
    This might sound nitpicking but inclusion is not exactly the same as concatenating scripts. Consider script1: `function myfunction() {` and script2: `alert();}` It won't work. It troubles me because I was trying to modularize a js file that's too long. See http://stackoverflow.com/questions/20311604/module-pattern-how-to-split-the-code-for-one-module-into-different-js-files/20311661?noredirect=1#20311661 – Boyang Dec 03 '13 at 00:46
  • Will this function share `this` context, if one of the function is in a class? – aks Aug 30 '16 at 04:51
  • 1
    `this` is bound at the point the function is called (unless `bind` is called beforehand). The two functions in two separate files will not share the `this` context automatically, in the above example neither has a `this` context, i.e. `window` in non-strict or `undefined` in strict mode. You can make the function in the other script share the same `this` value by either assigning the function as a member of the object (i.e. within the constructor `this.method = myOtherFunc`) or using bind. Please post a SO question with more detail if you need a more in depth answer. Cheers, Stuart – Stuart Wakefield Aug 30 '16 at 15:22
15

As long as both are referenced by the web page, yes.

You simply call the functions as if they are in the same JS file.

jball
  • 24,791
  • 9
  • 70
  • 92
11

ES6: Instead of including many js files using <script> in .html you can include only one main file e.g. script.js using attribute type="module" (support) and inside script.js you can include other files:

<script type="module" src="script.js"></script>

And in script.js file include another file like that:

import { hello } from './module.js';
...
// alert(hello());

In 'module.js' you must export function/class that you will import

export function hello() {
    return "Hello World";
}

Working example here.

Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
7

If all files are included , you can call properties from one file to another (like function, variable, object etc.)

The js functions and variables that you write in one .js file - say a.js will be available to other js files - say b.js as long as both a.js and b.js are included in the file using the following include mechanism(and in the same order if the function in b.js calls the one in a.js).

<script language="javascript" src="a.js"> and 
<script language="javascript" src="b.js">
Sayan
  • 2,053
  • 3
  • 25
  • 36
Pramendra Gupta
  • 14,667
  • 4
  • 33
  • 34
3

yes you can . you need to refer both JS file to the .aspx page

<script language="javascript" type="text/javascript" src="JScript1.js">
 </script>

    <script language="javascript" type="text/javascript" src="JScript2.js">
    </script>

JScript1.js

function ani1() {
    alert("1");
    ani2();
}
JScript2.js
function ani2() {
    alert("2");
}
anishMarokey
  • 11,279
  • 2
  • 34
  • 47
1

Here's a more descriptive example with a CodePen snippet attached:

1.js

function fn1() {
  document.getElementById("result").innerHTML += "fn1 gets called";
}

2.js

function clickedTheButton() {
  fn1();
} 

index.html

<html>
  <head>
  </head>
  <body>
    <button onclick="clickedTheButton()">Click me</button>
    <script type="text/javascript" src="1.js"></script>
    <script type="text/javascript" src="2.js"></script>
  </body>
 </html>

output

Output. Button + Result

Try this CodePen snippet: link .

Consta Gorgan
  • 549
  • 6
  • 22
1

For those who want to do this in Node.js (running scripts on the server-side) another option is to use require and module.exports. Here is a short example on how to create a module and export it for use elsewhere:

file1.js

const print = (string) => {
    console.log(string);
};

exports.print = print;

file2.js

const file1 = require('./file1');

function printOne() {
    file1.print("one");
};
ronatory
  • 7,156
  • 4
  • 29
  • 49
0

You can call the function created in another js file from the file you are working in. So for this firstly you need to add the external js file into the html document as-

<html>
<head>
    <script type="text/javascript" src='path/to/external/js'></script>
</head>
<body>
........

The function defined in the external javascript file -

$.fn.yourFunctionName = function(){
    alert('function called succesfully for - ' + $(this).html() );
}

To call this function in your current file, just call the function as -

......
<script type="text/javascript">
    $(function(){
        $('#element').yourFunctionName();
    });
</script>

If you want to pass the parameters to the function, then define the function as-

$.fn.functionWithParameters = function(parameter1, parameter2){
        alert('Parameters passed are - ' + parameter1 + ' , ' + parameter2);
}

And call this function in your current file as -

$('#element').functionWithParameters('some parameter', 'another parameter');
sheetal
  • 565
  • 6
  • 13
-1

Well, I came across another sweet solution.

window['functioName'](params);

Digvijay
  • 7,836
  • 3
  • 32
  • 53