In native JavaScript, before ES6 Modules 2015 has been introduced had no import, include, or require, functionalities. Before that, we can load a JavaScript file into another JavaScript file using a script tag inside the DOM that script will be downloaded and executed immediately. Now after the invention of ES6 modules there are so many different approaches to solve this problem have been developed and discussed below. ES6 Modules: ECMAScript (ES6) modules have been supported in Node.js since v8.5. In this module, we define exported functions in one file and import them in another example. There are two popular ways to call a JavaScript file from another function those are listed below:
- Ajax Techniques
- Concatenate files
Ajax Techniques Example:
External JavaScript file named “main.js”
Main file: This file will import the above “main.js” file
HTML
<!DOCTYPE html>
< html >
< head >
< title >
Calling JavaScript file from
another JavaScript file
</ title >
< script type = "text/javascript" >
let script = document.createElement('script');
script.src =
document.head.appendChild(script)
</ script >
</ head >
</ html >
|
Output:

Concatenate files Example: Here importing multiple JavaScript files into a single JavaScript file and calling that master JavaScript file from a function.
External JavaScript file named as “main.js”
External JavaScript file “second.js”
javascript
alert( "Welcome to Geeksforgeeks" )
|
External JavaScript file “master.js”
javascript
function include(file) {
let script = document.createElement( 'script' );
script.src = file;
script.type = 'text/javascript' ;
script.defer = true ;
document.getElementsByTagName( 'head' ).item(0).appendChild(script);
}
include(
include(
|
Main file: This file will import the above “master.js” file
HTML
<!DOCTYPE html>
< html >
< head >
< title >
Calling JavaScript file from
another JavaScript file
</ title >
< script type = "text/javascript"
</ script >
</ head >
< body >
</ body >
</ html >
|
Output: main.js file import:
second.js file import:

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!