I am trying to learn how different .js
files can be included in a HTML
file, so that my code bees more modular. I am following this page Can we call the function written in one JavaScript in another JS file?. I am confused at one point, that if I include files like this:
<script language="javascript" src="a.js">
<script language="javascript" src="b.js">
If a.js
contains:
function alertOne() {
alert("one");
}
and b.js
contains:
function alertTwo() {
alert("two");
}
then do I need to separately call the functions in HTML file or just including the files like <script language="javascript" src="b.js">
this, would execute alertTwo()
function?
I am trying to learn how different .js
files can be included in a HTML
file, so that my code bees more modular. I am following this page Can we call the function written in one JavaScript in another JS file?. I am confused at one point, that if I include files like this:
<script language="javascript" src="a.js">
<script language="javascript" src="b.js">
If a.js
contains:
function alertOne() {
alert("one");
}
and b.js
contains:
function alertTwo() {
alert("two");
}
then do I need to separately call the functions in HTML file or just including the files like <script language="javascript" src="b.js">
this, would execute alertTwo()
function?
- 2 A function is executed only when you call it. – MrUpsidown Commented Jan 27, 2014 at 13:42
- Including a Javascript file is essentially the same as just including the Javascript straight into the HTML, the function will not auto execute once included. – Nunners Commented Jan 27, 2014 at 13:43
- By the way. Did you try it by yourself? This is quite easy to test, IMO. – MrUpsidown Commented Jan 27, 2014 at 13:47
- Yes, I tried it myself and I couldn't understand the point, see my ment in Anthony's answer – user227666 Commented Jan 27, 2014 at 13:48
3 Answers
Reset to default 3Your JavaScript files are just declaring the functions. If you want them to actually execute then yes, you'd need to call them at some point. Whether that's inside another .js file, inside a <script>
tag in your HTML page, or as part of an event handler on an element, is up to you and depends on what exactly you want.
The code
function alertTwo() {
alert("two");
}
declares a function that can be called later
The code:
function alertTwo() {
alert("two");
}
alertTwo();
declares a function, and then immediately calls it.
The code:
(function alertTwo() {
alert("two");
})();
declares a function that immediately calls itself.
It doesn't matter if your code is directly in the HTML file, or included via script
tag. Nothing is "executed" or done special via script
tag. It's effectively like saying "paste the stuff from that file here."
The function alertOne()
in a.js
can be called from b.js
if both a.js
and b.js
are included in your HTML.