HOWTO · JavaScript
How to Import Function From Another JS File
Learn how to call a function from another JavaScript file with browser scripts, ECMAScript modules, Node.js CommonJS, or legacy jQuery.
On this page
To call a function from another JavaScript file, choose the sharing method for the environment: classic <script> tags expose a browser global, ECMAScript modules use export and import, and Node.js CommonJS uses module.exports and require. The examples below show how to connect the files and where each approach runs.
Call a Function From Another JavaScript File in a Browser
For a page using classic scripts, define the function in one file and load that file before the script that calls it. Classic scripts share the page’s global scope, so the first file can attach a function to window:
- In
greeting.js, writewindow.showGreeting = function () { document.querySelector("#message").textContent = "Hello from greeting.js"; };. - In
app.js, writedocument.querySelector("#show").addEventListener("click", window.showGreeting);.
Save these files beside index.html. This page loads them in the required order and provides the button and message element:
<!doctype html>
<html lang="en">
<meta charset="utf-8">
<title>Call a function from another file</title>
<p id="message">Click the button to show the message.</p>
<button id="show" type="button">Show greeting</button>
<script src="greeting.js"></script>
<script src="app.js"></script>
</html>
When the button is clicked, the handler in app.js calls the function loaded from greeting.js. Keep the defining script first; otherwise the page may try to register a handler before window.showGreeting exists. The html block is a browser-page example and is not a runtime output transcript.
Share Functions With ECMAScript Modules
Use ECMAScript modules when you want explicit imports instead of a shared global. Save these three complete files in the same directory. The first file exports a function, and the second imports it and updates the page:
greeting.js:export function makeGreeting(name) { return \Hello, ${name}!`; }`app.js:import { makeGreeting } from "./greeting.js"; document.querySelector("#message").textContent = makeGreeting("Ada");
Save this complete page as index.html beside those files. Its message element is present before the module runs:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Share a function with a module</title>
</head>
<body>
<p id="message">The greeting will appear here.</p>
<script type="module" src="app.js"></script>
</body>
</html>
Keep the relative import path aligned with the file locations. Browsers load modules with module semantics and do not put their declarations on window.
Serve the page over HTTP with a local development server; opening it directly as a file: URL commonly prevents module loading. This is a browser hosting requirement, not a requirement to run Node.js. Node.js also supports ECMAScript modules, with its own package and file-extension rules. The ECMAScript module export syntax uses the same export mechanism for functions and other values.
Import Functions With CommonJS in Node.js
CommonJS is Node.js’s traditional module system. A module can assign a function to module.exports, and another file can retrieve it with require. The linked comparison of JavaScript import and require explains how these module systems differ.
This self-contained Node.js example creates a helper file, imports its function, and calls it. Save the code as main.cjs and run node main.cjs from a terminal with Node.js installed:
const fs = require("node:fs");
const os = require("node:os");
const path = require("node:path");
const folder = fs.mkdtempSync(path.join(os.tmpdir(), "function-demo-"));
try {
const helperPath = path.join(folder, "math.cjs");
fs.writeFileSync(helperPath, "module.exports = (a, b) => a + b;\n");
const add = require(helperPath);
console.log(`Result: ${add(5, 3)}`);
} finally {
fs.rmSync(folder, { recursive: true, force: true });
}
Result: 8
The helper file exports one function, and the caller receives it as the return value of require; the final console.log call uses that returned function. The .cjs extension makes the helper’s CommonJS format explicit even when the surrounding project uses ECMAScript modules. This example is written for Node.js and does not run in a browser page.
Load a JavaScript File With jQuery
jQuery’s $.getScript() can load a script on demand. This is a legacy alternative for pages that already use jQuery; new code will usually be clearer with browser modules or ordinary script tags. Load jQuery before the caller, and wait for the load callback before using the function from the downloaded file.
For example, mathUtils.js can expose a browser global with window.mathUtils = { add: (a, b) => a + b };. In the page, load jQuery first and use the callback to call the function after the script has loaded:
<script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
<script>
$.getScript("mathUtils.js")
.done(function () {
const result = window.mathUtils.add(5, 3);
$("body").append(`<p>Result: ${result}</p>`);
})
.fail(function () {
$("body").append("<p>The script could not be loaded.</p>");
});
</script>
The request is asynchronous, so code that depends on mathUtils belongs inside .done() (or another completion handler), not immediately after $.getScript(). For a cross-origin URL, jQuery can load the script through a script element; browsers generally do not require CORS for that kind of script loading. A cross-origin fetch() or XHR request does require the server to allow it with CORS. Script loading can still be blocked by browser policies such as Content Security Policy, or fail if the URL is unreachable. See the jQuery $.getScript() documentation for its loading behavior.