I am trying to call a function written in one JavaScript file from another JavaScript file. I have the following code, but it doesn't work:
<script type="text/javascript" src="js1.js"></script>
<script type="text/javascript" src="js2.js"></script>
<script language="javascript">
js1();
</script>
function js1()
{
alert("Hello from js1");
js2();
}
function js2()
{
alert("Hello from js2");
}
What can I do?
Calling a function using external JavaScript fileWe can also call JavaScript functions using an external JavaScript file attached to our HTML document.
write('<script src="myscript. js" type="text/javascript"></script>'); If you use the jQuery library, you can use the $. getScript method.
Try changing the order
<script type="text/javascript" src="js2.js"></script>
<script type="text/javascript" src="js1.js"></script>
<script language="javascript">
js1();
</script>
Because you call js2();
inside js1.js
, so the script js2.js
should be executed before.
In your case, i think it should still work without changing orders like this because you call js2();
inside a function. When this script is executed:
function js1()
{
alert("Hello from js1");
js2();
}
Even the js2.js
is not executed yet, but you do not actually call js2();
at this time.
Just try it to see if it works.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With