简体   繁体   中英

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>

I would recomend have separate external js files instead of an embedded <script> tag, but maybe this can help

How to include js file in another js file?

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");
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM