How to Include JavaScript File in Another JavaScript File

Often web developers need to include a JavaScript file in another JavaScript file to avoid code rewrite and make their code modular. It is also required if you have large amount of JS code and you want to split it across multiple files. There are several ways to do this. In this article, we will learn how to import a JavaScript file into another JavaScript file. You can use these methods to import one or variables as well as functions from one file to another. They are supported by most modern web browsers.

What are ES6 Modules

Before we proceed, we need to learn a bit about ES6 modules. ES6 stands for ECMA Script 6, launched in 2015. It is a core JavaScript feature that allows you to easily import external JavaScript files to other JavaScript/HTML files. An ES6 module is simply a JavaScript file whose variables and functions can be exported to other files, and which can also import functions & variables from other files. It is supported by many modern browsers. It allows you to split your code into multiple files and directories, such that their contents can be accessed by each other. It is very useful in building JS libraries and modules. Before 2015, this was not supported and developers had to rely on third party JS libraries for this purpose.

How to Include JavaScript File in Another JavaScript File

There are several ways to include JavaScript File to another. Let us look at each of them in detail. Let us say you have 3 files – 1 HTML file test.html, and 2 JavaScript files main.js and lib.js. Let us see how to use them as per various use cases.

1. Using Export/Import

In this approach, we include JavaScript file using import/export keywords natively supported by JavaScript ES6. Let us say you have the following function in lib.js to add 2 numbers. We have also included a test_var just to demonstrate how to export variables.

export function add(a, b){
return a+b;
}

export test_var='hello world';

Please note, unlike regular JavaScript functions, we have added export keyword at the beginning of our function and variable, indicating that they can be exported to other files.

Let us import this function as well as the variable in main.js file. You need to use import { object1, object2, …} syntax to import functions and variables from another file. In this case, both variables and functions are seen as JS objects.

import { add, test_var } from "./lib.js"

Here both lib.js and main.js files are in the same directory. If the JS file is in a different directory than JS module, then you need to specify the directories as per your requirement.

Thereafter, you can use it in a regular JS code. Here is an example to use it in regular JS function.

function hello(){
console.log(add(1,2)); //prints 3 in console
}

Or in another function that can also be exported.

export function hello(){
console.log(add(1,2)); //prints 3 in console
}

2. Using ES6 Modules

In the above case, we learnt how to import one JS file to another. What if you want to include JavaScript file into an HTML file? You can do this by using script tag, as you would do to import any JS file, along with mentioning type=”module”, in the head or body of the page.. Let us say you have the following HTML code in file test.html.

<!DOCTYPE html>
<html lang="en">
<head>
<script src="main.js" type="module"></script>
</head>
<body>
Hello World
</body>
</html>

The type=’module’ attribute of script tag allows your JS file to contain import and export statements.

Alternatively, you can add an import statement in script tag as shown below.

<!DOCTYPE html>
<html lang="en">
<head>
<script type="module">
import { add } from "./lib.js"
console.log(add(1, 2)); //prints 3 in console

</script>
</head>
<body>
Hello World
</body>
</html>

You can also these script tags in HTML body, if you want.

3. Using DOM Manipulation

Another simple way to include JS file into your web page is by dynamically adding the script tag that imports JS file to it. In this case, we will use JavaScript code to include JavaScript file to another file. Here is a sample code to import main.js file to test.html using plain JavaScript.

<!DOCTYPE html>
<html>
<head>
<title>
Importing JS file to HTML
</title>
<script type="text/javascript">
let script = document.createElement('script');
script.src ="./main.js";
document.head.appendChild(script)
</script>

</head>
</html>

In the above HTML code, we first create a script tag. Inside this script tag, we add the JavaScript code to import our main.js file. For this, we create another script tag using document.createElement() function. Then we set its src attribute to the location of main.js. Lastly, we append the newly created script tag to the head of the web page, using document.head.appendChild() function. This will execute any function calls in main.js.

It is very flexible and easy way to import JS files into other files, without using modules. It also provides good control as to when you want the JS file to be available since you can add the script tag as and when required.

4. Import Multiple Files

You can use the above method to include multiple files in your web page. Let us create a JavaScript function where we accept JS file path as input, create a script tag with this path as its src attribute and then append the script tag to the head of the page.

function js_include(file_path) {

let script = document.createElement('script');
script.src = file_path;
script.type = 'text/javascript';
script.defer = true;

document.getElementsByTagName('head').item(0).appendChild(script);

}

js_include('./lib1.js');
js_include('./lib2.js');

Thereafter, you can call this function in your web page as shown in the last 2 lines above. Now if you put all the above code in another file main.js and import it to your web page, then it will automatically also import lib1.js and lib2.js.

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="./main.js"> </script>
</head>

<body>
</body>
</html>

5. Dynamic Imports Using Async/Await

If the imported file is too large, and you are not sure if you want to import it immediately, then you can use Aync/Await feature to import this file only when you need it. This improves page load speed by not importing your file upfront. Here is the lib.js file as defined before.

export function add(a, b){
return a+b;
}

export test_var='hello world';

Here is the code in main.js to import lib.js file only when a button is clicked.

const button = document.querySelector("button");
button.addEventListener("click", async () => {
const lib = await import("./lib.js");
console.log(lib.add(1,2));
});

In the above code, we use import() function along with path to lib.js to import the file. But we call it after await keyword so that it is not called right away but only returns a promise. This whole thing happens inside the click event handler of the button element.

Benefits of Importing JS File

There are several benefits of using JavaScript modules:

  1. JS modules make it easy to break your code into smaller pieces that are easy to manage.
  2. It reduces code rewriting and modularizes your code.
  3. It makes your code easy to understand.
  4. It allows you to easily reuse code from other parts of your application, without having to build things from scratch.

Conclusion

In this article, we have learnt several different ways to include JavaScript file to another JavaScript file using modules. However, there are key points to remember while working JS modules. First, they always use strict mode and their functions and variables are available only to those files where they are imported. They are not available to the global namespace. Also, they cannot be loaded locally using file:// protocol but only from within another HTML or JS file. You can use any of these methods as per your requirement.

Also read:

How to Clone Objects in JavaScript
How to Detect Browser in JavaScript
How to Check if Element is Hidden jQuery
How to Access Correct This Inside Callback

Leave a Reply

Your email address will not be published. Required fields are marked *