HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptCritical

How do I include a JavaScript file in another JavaScript file?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
howfileincludejavascriptanother

Problem

How do I include a JavaScript file inside another JavaScript file, similar to @import in CSS?

Solution

The old versions of JavaScript had no import, include, or require, so many different approaches to this problem have been developed.

But since 2015 (ES6), JavaScript has had the ES6 modules standard to import modules in Node.js, which is also supported by most modern browsers.

For compatibility with older browsers, build tools like Webpack and Rollup and/or transpilation tools like Babel can be used.
ES6 Modules

ECMAScript (ES6) modules have been supported in Node.js since v8.5, with the --experimental-modules flag, and since at least Node.js v13.8.0 without the flag. To enable "ESM" (vs. Node.js's previous CommonJS-style module system ["CJS"]) you either use "type": "module" in package.json or give the files the extension .mjs. (Similarly, modules written with Node.js's previous CJS module can be named .cjs if your default is ESM.)

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 modules in browsers

Browsers have had support for loading ECMAScript modules directly (no tools like Webpack required) since Safari 10.1, Chrome 61, Firefox 60, and Edge 16. Check the current support at caniuse. There is no need to use Node.js' .mjs extension; browsers completely ignore file extensions on modules/scripts.

import { hello } from './hello.mjs'; // Or the extension could be just
.js
hello('world');


// hello.mjs -- or the extension could be just .js
export function hello(text) {
const div = document.createElement('div');
div.textContent =
Hello ${text};
document.body.appendChild(div);
}


Read more at https://jakearchibald.com/2017/es-modules-in-browsers/
Dynamic imports in browsers

Dynamic imports let the script load other scripts as needed:

import('hello.mjs').then(module => {
module.hello('world');
});



Read more at https://developers.google.com/web/updates/2017/11/dynamic-import
Node.js require

The older CJS module style, still widely used in Node.js, is the module.exports/require system.
// mymodule.js
module.exports = {
hello: function() {
return "Hello";
}
}

// server.js
const myModule = require('./mymodule');
let val = myModule.hello(); // val is "Hello"


There are other ways for JavaScript to include external JavaScript contents in browsers that do not require preprocessing.
AJAX Loading

You could load an additional script with an AJAX call and then use eval to run it. This is the most straightforward way, but it is limited to your domain because of the JavaScript sandbox security model. Using eval also opens the door to bugs, hacks and security issues.
Fetch Loading

Like Dynamic Imports you can load one or many scripts with a fetch call using promises to control order of execution for script dependencies using the Fetch Inject library:

fetchInject([
  'https://cdn.jsdelivr.net/momentjs/2.17.1/moment.min.js'
]).then(() => {
  console.log(`Finish in less than ${moment().endOf('year').fromNow(true)}`)
})


jQuery Loading

The jQuery library provides loading functionality in one line:
$.getScript("my_lovely_script.js", function() {
alert("Script loaded but not necessarily executed.");
});

Dynamic Script Loading

You could add a script tag with the script URL into the HTML. To avoid the overhead of jQuery, this is an ideal solution.

The script can even reside on a different server. Furthermore, the browser evaluates the code. The ` tag can be injected into either the web page , or inserted just before the closing tag.

Here is an example of how this could work:
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 will add a new
tag to the end of the head section of the page, where the src` attribute is set to the URL which is given to the function as the first parameter.

Both of these solutions are discussed and illustrated in JavaScript Madness: Dynamic Script Loading.
Detecting when the script has been executed

Now, there is a big issue you must know about. Doing that implies that you remotely load the code. Modern web browsers will load the file and keep executing your current script because they load everything asynchronously to improve performance. (This applies to both the jQuery method and the manual dynamic script loading method.)

It means that if you use these tricks directly, you won't be able to

Code Snippets

import { hello } from './module.js';
let val = hello();  // val is "Hello";
export function hello() {
  return "Hello";
}
import { hello } from './module.mjs';
let val = hello();  // val is "Hello";
fetchInject([
  'https://cdn.jsdelivr.net/momentjs/2.17.1/moment.min.js'
]).then(() => {
  console.log(`Finish in less than ${moment().endOf('year').fromNow(true)}`)
})

Context

Stack Overflow Q#950087, score: 5483

Revisions (0)

No revisions yet.