Calling a function from one JavaScript file that 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 does not 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?

+4
source share
2 answers

Try to reorder

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

Because you are calling js2(); inside js1.js , so the js2.js script should be executed earlier.

In your case, I think it should still work without changing the order, since you are calling js2(); inside the function. When this script is executed:

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

Even js2.js is not executed yet, but you are not actually calling js2(); at that time.

Just try to see if it works.

+4
source

I am going to assume that your entire HTML page.

In order for these scripts to run, you need to have these JavaScript files in the same folder as your web page, and actually have a proper HTML page!

On your HTML page, you need to include links to the js1 and js2 files in the head or body and include the script that you wrote on the HTML page itself in the body so that it will execute on loading:

 <!DOCTYPE html> <!-- ^ Declaring this DOCTYPE means this is a HTML5 page. --> <html> <head> <!-- This will load your scripts into the document. --> <script src="js1.js"></script> <script src="js2.js"></script> <!-- In a HTML5 page, you don't need to include the 'type="text/javascript"' attribute on script tags. They're treated as having that by default, unless you say otherwise. --> </head> <body> <!-- You could also include your scripts here, but I'll just leave these commented out since they're already included. <script src="js1.js"></script> <script src="js2.js"></script> --> <script> js1(); </script> <!-- You don't need 'language="javascript"' on a script tag. Use the type attribute, or nothing in a HTML5 page. --> </body> </html> 
+2
source

Source: https://habr.com/ru/post/1489833/


All Articles