Reputation: 109
<html>
<head>
<script src="./first.js"></script>
<script src="./second.js"></script>
</head>
</html>
In the first.js file, I want to call the functions from second.js:
secondFun(); // calling a function from second.js file
This is second.js file:
function secondFun() {
console.log('second function called!!')
}
Upvotes: 4
Views: 31386
Reputation: 1347
Use import/export
introduced in ECMAScript 6 (ES6) specification.
second.js
export function secondFun() {
console.log('second function called!!')
}
first.js
import { secondFun } from 'second.js';
Then call secondFun()
in the first file.
Upvotes: 8
Reputation: 943759
tl;dr: Load your dependencies before you depend on them.
You can't call a function that hasn't been loaded.
The functions defined in your second JS file won't be loaded until the first file has finished running all the top-level statements.
Reverse the order of your script elements.
Upvotes: 8
Reputation: 74738
You are trying to access a function which i not in available yet there. So, you can't use in such case. But what you can do:
defer
attribute on the script file.You have to load your functions before to use them. So, reverse the order of the scripts.
defer
Attribute is one of the seldom used attributes. As you can probably tell by the name of the attribute, defer instructs the contents of the script tag to not execute until the page has loaded.
Upvotes: 0
Reputation: 1874
in second.js
document.addEventListener("DOMContentLoaded", function(event) {
function secondFun(){
console.log('second function called!!')
}
});
haven't test but suppose to work
Even your js not right queue function order this function will wait until all files loaded to execute
Upvotes: 0
Reputation: 857
A function cannot be called unless it was defined in the same file or one loaded before the attempt to call it.
A function cannot be called unless it is in the same or greater scope then the one trying to call it.
You declare function fn1 in first.js, and then in second you can just have fn1();
1.js :
function fn1 (){
console.log('second function called!!')
}
2.js :
fn1();
index.html :
<script type="text/javascript" src="1.js"></script>
<script type="text/javascript" src="2.js"></script>
It works fine :)
Upvotes: 5