How to Include a JavaScript File in Another JavaScript File

Before the introduction of the ES6 modules, JavaScript didn’t have import, require, or other functionalities. In 2015, the ES6 Modules module was introduced, which now makes it possible to import modules in Node.js supported by modern browsers.

ES6 Modules

Node.js v13.8.0 supports ECMAScript (ES6) modules without any flag. However, all the files included must have the .js extension:

// module.js
export function welcome() {
  return "Welcome";
}
// main.js
import {
  welcome
} from './module.js';
let value = welcome(); // val is "Welcome";

Node.js require

The module.exports/require system old method of importing modules is still used in Node.js.

// mymodule.js
module.exports = {
  welcome: function () {
    return "Welcome";
  }
}
// server.js
const myModule = require('./mymodule');
let val = myModule.welcome(); // val is "Welcome"

Some other ways exist that do not require processing.

AJAX Loading

Loading a script can be possible with an AJAX call and eval function. Even though this is the most straightforward way, it is limited to your domain because of the JavaScript sandbox security model.

Eval can cause bugs and other security issues.

jQuery Loading

Loading with jQuery can be done by just one line:

.getScript("script.js", function () {
  alert("The script is loaded but not necessarily executed.");
});

Dynamic Script Loading

The perfect solution will be adding a script tag with the script URL into the HTML. The <script> tag can be added into either the <head> or before the closing </body> tag to avoid the overhead of jQuery.

function dynamicallyLoadScript(url) {
  let loadScript = document.createElement("script"); // create a script DOM node
  loadScript.src = url; // set its src to the provided URL
  document.head.appendChild(loadScript);
}

Do you find this helpful?

Related articles