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