In native JavaScript, before ES6 Modules 2015 was 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:
Table of Content
Ajax Techniques
- We are creating a file named main.js and app.js.
- In the app.js file, we are importing the main.js.
- In app.js, We are creating an element named “script” and setting its source link equal to the main.js.
- Then we are appending that “script” element into the head of the app.js file.
- After loading the file into the browser it shows the alert first.
Example: External JavaScript file named “main.js”
// This alert will export in the main file alert( "Hello Geeks" )
|
Main file: This file will import the above “main.js” file
<!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
- In this approach, we are creating three files named main.js, second.js, and master.js.
- master.js file is importing the rest of the two files by using include function.
- We are setting the src eqaul to the file link.
- After loading the file it shows the output accrding to the written code in both of the imported 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”
// This alert will export in the main file alert( "Hello Geeks" )
|
External JavaScript file “second.js”
// This alert will export in the main file alert( "Welcome to Geeksforgeeks" )
|
External JavaScript file “master.js”
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 Many js files */ include( include( |
Main file: This file will import the above “master.js” file
<!DOCTYPE html> < html >
< head >
< title >
Calling JavaScript file from
another JavaScript file
</ title >
< script type = "text/javascript"
</ script >
</ head >
< body >
</ body >
</ html >
|
Output: It is showing both the alerts from main.js and second.js according to the sequence of including both of the files in master.js.