Can we call the function written in one JavaScript in another JS file?
Asked Answered
R

10

208

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?

Rhoden answered 28/9, 2010 at 5:13 Comment(0)
Q
228

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).

Quirites answered 28/9, 2010 at 5:22 Comment(1)
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.Rufus
A
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.

Alkalinity answered 28/9, 2010 at 10:22 Comment(3)
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 #20312104Eft
Will this function share this context, if one of the function is in a class?Crucial
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, StuartAlkalinity
T
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.

Titty answered 28/9, 2010 at 5:15 Comment(0)
S
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.

Salad answered 25/4, 2019 at 5:23 Comment(0)
E
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">
Euler answered 28/9, 2010 at 5:24 Comment(0)
W
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");
}
Woodbury answered 28/9, 2010 at 5:19 Comment(0)
S
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 .

Spancake answered 17/9, 2018 at 15:12 Comment(0)
T
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");
};
Tartarus answered 26/5, 2020 at 18:8 Comment(0)
M
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');
Morehouse answered 29/3, 2017 at 7:33 Comment(6)
Please don't assume jQuery everywhere. Also, wrapping the $.fn assignment in a document ready clause is pointlessSiloam
okay i'll keep it mind next time :), but can you explain why $.fn assignment is pointless?Morehouse
Not the assignment, the wrapping.Siloam
okay so that means when document is not ready, only then $.fn should be used for creating functionMorehouse
But why? The declaration the function doesn't need to wait for the DOM. Even if the call might (but often enough it doesn't).Siloam
i am sorry, I don't know, that was why I was asking :| Can you make me understand it?Morehouse
V
-1

Well, I came across another sweet solution.

window['functioName'](params);

Valuation answered 21/4, 2020 at 13:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.