Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a function from one JavaScript file which requires another

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:

My HTML file

<script type="text/javascript" src="js1.js"></script>
<script type="text/javascript" src="js2.js"></script>
<script language="javascript">
    js1();
</script>

js1.js

function js1()
{
    alert("Hello from js1");
    js2();
}

js2.js

function js2() 
{
    alert("Hello from js2");
}

What can I do?

like image 402
AloNE Avatar asked Jul 05 '13 04:07

AloNE


People also ask

Can you call a function from another JavaScript file?

Calling a function using external JavaScript fileWe can also call JavaScript functions using an external JavaScript file attached to our HTML document.

How do you call another JS file in JS?

write('<script src="myscript. js" type="text/javascript"></script>'); If you use the jQuery library, you can use the $. getScript method.


1 Answers

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.

like image 145
Khanh TO Avatar answered Oct 24 '22 21:10

Khanh TO