How to Include a JavaScript File in Another JavaScript File?

Previous versions of JavaScript had no imports, inclusions or requirements, so different approaches to this problem have been developed.

However, since 2015 (ES6), JavaScript has a standard ES6 module for importing modules into Node.js, which is also supported by most modern browsers.
Include a JavaScript file in Another JavaScript
For compatibility with older browsers, you can use build tools like Webpack and Rollup and conversion tools like Babel.

ES6 module

ECMAScript (ES6) modules are supported in Node.js since v8.5, with the -experimental-modules flag, and at least since Node.js v13.8.0, without the flag. To enable “ESM” (versus the previous CommonJS style module system in Node.js [“CJS”]), use "type": "module" in package.json or in a file Add the .mjs extension. (Similarly, if the default is ESM, a module written in an older CJS Node.js module can be named .cjs.)

Using package.json:

"type": "module"

Then module.js:

export function hello() {
return "Hello";

Then main.js:

import { hello } from './module.js';
let val = hello(); // val is "Hello";

Using .mjs, you’d have module.mjs:

export function hello() {
return "Hello";

Then main.mjs:

import { hello } from './module.mjs';
let val = hello(); // val is "Hello";

ECMAScript browser module

The browser supports direct loading of ECMAScript modules from Safari 10.1, Chrome 61, Firefox 60 and Edge 16 (no tools such as Webpack are required). Check out the current support for can use. It is not necessary to use the Node.js .mjs extension. The browser completely ignores the module / script file extension.

<script type="module">
import { hello } from './hello.mjs'; // Or it could be simply `hello.js`
// hello.mjs -- or it could be simply `hello.js`
export function hello(text) {
const div = document.createElement('div');
div.textContent = `Hello ${text}`;

Dynamic import into the browser

Dynamic import allows a script to load other scripts as needed.

<script type="module">
import('hello.mjs').then(module => {

Node.js require

The old-fashioned CJS module that is still widely used in Node.js is module.exports / requiresystem.

// anymodule.js
module.exports = {
hello: function() {
return "Hello";
// server.js
const anymodule= require('./anymodule');
let val = anymodule.hello(); // val is "Hello"

There are other ways that JavaScript can include external JavaScript content in browsers that don’t require preprocessing.

AJAX loading

Additional scripts can be loaded with AJAX calls and executed using eval. This is the simplest way, but it is domain specific due to the JavaScript sandbox security model. eval also opens the door to bugs, hacks, and security problems.

Fetch the load

Similar to dynamic imports, you can use promises to load one or more scripts into fetch calls and use the FetchInject library to control the execution order of script dependencies.

]).then(() => {
console.log(`Finish in less than ${moment().endOf('year').fromNow(true)}`)

Loading JQuery

The jQuery library offers the ability to read a single line.

$.getScript("m_script.js", function() {
alert("Script loaded but not necessarily executed.");

Dynamic script loading

You can add script tags using the script URL in the HTML code. This is the ideal solution to avoid jQuery overload.

The script can also reside on another server. Also, the browser evaluates the code. The <script> tag can be placed on the web page <head> or just before the end </body> tag.

Here is an example of how it works:

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

document.head.appendChild(script); // add it to the end of the head section of the page (could change 'head' to 'body' to add it to the end of the body section instead)

This function adds a new <script> tag at the end of the head section of the page. Here, the src attribute is set to the URL specified in the function as the first parameter.

Detect when the script was executed

Now, there is a big problem that you should be aware of. To do this, you need to upload the code remotely. Modern web browsers load everything asynchronously to improve performance, then load the files and continue to run the current script. (This applies to both the jQuery method and the manual dynamic script loading method.)

This means that if you use these cheats directly, the newly uploaded code is still loaded and you cannot redeem the code on the next line after requesting an upload.

Example: my_script.js contains MySuperObject:

var js = document.createElement("script");
js.type = "text/javascript";
js.src = jsFilePath;
var s = new MySuperObject();
Error : MySuperObject is undefined

Then you reload the page hitting F5. And it works! Confusing…

So what do you do with it?

Well, you can use the hack suggested by the author in the link I gave you. In summary, for those in a hurry, we use an event to execute a callback function when the script is loaded. Therefore, you can use the remote library to put all your code into the callback function. for instance:

function loadScript(url, callback)
// Adding the script tag to the head as suggested before
var head = document.head;
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = url;
// Then bind the event to the callback function.
// There are several events for cross browser compatibility.
script.onreadystatechange = callback;
script.onload = callback;
// Fire the loading

Then, write the code to use after the script is loaded into the lambda function.

var myPrettyCode = function() {
// Here, do whatever you want

Then you throw it all away:

loadScript("my_script.js", myPrettyCode);

Note that the script can be run after or before the DOM loads, depending on the browser and whether you included the script.async = false; line. There is a good article on loading JavaScript in general that explains this.

Source code merger / preprocessing

As mentioned at the beginning of this answer, many developers use compile / transpiling tools like Parcel, Webpack, Babel in their projects. This allows you to use future JavaScript syntax to provide backward compatibility for older browsers. Split cable etc.

Data Source:

Leave a Reply