Skip to content
Advertisement

Call JavaScript function from another JavaScript file

<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!!')
}

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement