How to Include a JavaScript File in Another JavaScript File
Read the tutorial and find out different approaches to including a JavaScript file in another JavaScript file. Also, find a brief representation of methods.
Before the introduction of ES6 modules, JavaScript did not have import, require, or other built-in module functionalities. In 2015, the ES6 modules specification was introduced, making it possible to import modules in Node.js and modern browsers.
ES6 Modules
Node.js v14.0.0 supports ECMAScript modules without any flags. All files must use the .js extension:
// module.js
export function welcome() {
return "Welcome";
}
// main.js
import { welcome } from './module.js';
let value = welcome(); // value is "Welcome"Node.js require
The module.exports/require system is a legacy method of importing modules that is still widely 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"jQuery Loading
jQuery previously provided a .getScript() method for loading scripts. Note that this method was removed in jQuery 4.0. For modern projects, use the vanilla JavaScript approach described below.
// Legacy jQuery example (removed in jQuery 4.0)
$.getScript("script.js", function () {
alert("The script is loaded but not necessarily executed.");
});Dynamic Script Loading
A reliable approach is to dynamically add a <script> tag to the document. You can append it to the <head> or just before the closing </body> tag to avoid the overhead of a library like 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);
}