Ande Mohit
Ande Mohit

Reputation: 109

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

Upvotes: 4

Views: 31386

Answers (5)

Vishal-L
Vishal-L

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

Quentin
Quentin

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

Jai
Jai

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:

  1. Reverse the order.
  2. Use defer attribute on the script file.

1.

You have to load your functions before to use them. So, reverse the order of the scripts.

2. Source

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.

Demo@plnkr

Upvotes: 0

Munkhdelger Tumenbayar
Munkhdelger Tumenbayar

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

Reda Maachi
Reda Maachi

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

Related Questions