0

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>
coderpc
  • 4,119
  • 6
  • 51
  • 93
Yash
  • 198
  • 1
  • 12
  • Export scripts to a JS file and import it on both pages – Rajesh Mar 17 '20 at 06:47
  • You cannot use HTML as a src for a JS file. You need app1.js that contains only `function greet() { alert('hello from App1') }` – mplungjan Mar 17 '20 at 06:49
  • Thank you guys for the help! – Yash Mar 18 '20 at 09:42
  • One more question. Do you know how scripts(line execution) work in HTML code. So I am requiring app1 and app2 file in my app3.html, And if I call the method in app3.js (method name is same from both file). So only the method from file that is written lowest gets called. Ex:- only greet of app1.js will be called coz it is written lowest. – Yash Mar 18 '20 at 09:43
  • @YashJaiswal same thing goes with that as well, it won't make much difference you just have to add reference of 2 files in 3rd file(app3.html) and call whichever method you want to trigger. – Manjuboyz Mar 18 '20 at 09:47
  • Kindly vote the answer if you think worth voting, thanks. – Manjuboyz Mar 18 '20 at 09:47

2 Answers2

0

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?

  • 1
    Whilst this may theoretically answer the question, [it would be preferable](//meta.stackoverflow.com/q/8259) to include the essential parts of the answer here, and provide the link for reference. – mplungjan Mar 17 '20 at 06:52
0

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");
 }
Manjuboyz
  • 6,978
  • 3
  • 21
  • 43