I have 2 external javaScript files. I want to call a function
of first file into second file.
any body can help me?
How i can call a function from external javascript file in another external javascript file?
Asked
Active
Viewed 1,339 times
-2

Govind Singh
- 15,282
- 14
- 72
- 106
-
2possible duplicate of [How to include a JavaScript file in another JavaScript file?](http://stackoverflow.com/questions/950087/how-to-include-a-javascript-file-in-another-javascript-file) – andrewdotnich Jul 03 '14 at 06:31
3 Answers
2
JS
prints the values on DOM, so once the page has been rendered on the browser, it is all treated as one large document. This means, after parsing, you can call any function from any JS file ONLY IF that function has been loaded on DOM before your calling function!
That explained, assuming you have 2 files js1.js
and js2.js
,having fn1()
in js1 and fn2()
in js2
So if you have to call fn1()
in js1.js
, load it before js2.js
, once loaded simply make a call to fn1()
from js2.js
and it would work!!
js1.js
function fn1(){
// some code
}
js2.js
function fn2(){
fn1(); //function call to another file.
}
Just ensure the order of loading :
<script src="js1.js" type="script/javascript"> <!-- Load the main program JS first -->
<script src="js2.js" type="script/javascript"> <!--Load the calling program JS after it -->
One additional way of doing it
<script src="js1.js" type="script/javascript"> //Load the main program JS first
<script language="javascript">
fn1(); //call the function directly from the HTML embedded JS :)
</script>

NoobEditor
- 15,563
- 19
- 81
- 112
2
import both js file into a single html page, and then any function you want to call from any where you want
html
<html>
//
<script type="text/javascript" src="1st.js"></script>
<script type="text/javascript" src="2nd.js"></script>
//
</html>
1st.js
function js1(){
//...
}
2nd.js
function js2(){
js1();
}

Govind Singh
- 15,282
- 14
- 72
- 106
2
- You have to make sure that script from which you are calling your function is downloaded after the script in which you have your function;
- And, of course, that the place from where you are calling you function has scope access to the function you call.

BenMorel
- 34,448
- 50
- 182
- 322

Vlas Bashynskyi
- 1,886
- 2
- 16
- 25