Search code examples
javascripthtmlfunctionimportinclude

How do I link a Javascript file into another Javascript file


There are two files here in the same folder. I am trying to invoke a function named greet of app1 in app2.

app1.html

<script>
  function greet() {
    alert('hello from App1')
  }
  // greet() // commented out code
</script>

app2.html

<script type="text/javascript" src="./app1.html"></script>
<script>
  function app2() {
    alert('app2')
  }
  app2()
  greet() // this line of code is not working
</script>

Solution

  • If you want to call the file in an another js file then you have to refer that file in the calling file.

    Ex.

    Refer the files in the head section.

      <head>     
        <script src="File2.js" type="text/javascript"></script> 
        <script src="File1.js" type="text/javascript"></script> 
      </head>
    

    you can have your body tag something like this:

    <body>
      <script type="text/javascript">
       Method2(); // Where you want to call method from another JS.
      </script>
     </body>
    

    then, using first file

    File1.js

    function Method1(number) {
      alert("Method1");
    }
    

    File2.js

    function Method2() {
     Method1("Method1 is called in Method2");
     }