Categories
Dev

How to include a JavaScript file in another JavaScript file?

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:

<span class="hljs-punctuation">{</span>
    <span class="hljs-attr">"type"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"module"</span>
<span class="hljs-punctuation">}</span>

Then module.js:

<span class="hljs-keyword">export</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">hello</span>() {
  <span class="hljs-keyword">return</span> <span class="hljs-string">"Hello"</span>;
}

Then main.js:

<span class="hljs-keyword">import</span> { hello } <span class="hljs-keyword">from</span> <span class="hljs-string">'./module.js'</span>;
<span class="hljs-keyword">let</span> val = <span class="hljs-title function_">hello</span>();  <span class="hljs-comment">// val is "Hello";</span>

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

<span class="hljs-keyword">export</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">hello</span>() {
  <span class="hljs-keyword">return</span> <span class="hljs-string">"Hello"</span>;
}

Then main.mjs:

<span class="hljs-keyword">import</span> { hello } <span class="hljs-keyword">from</span> <span class="hljs-string">'./module.mjs'</span>;
<span class="hljs-keyword">let</span> val = <span class="hljs-title function_">hello</span>();  <span class="hljs-comment">// val is "Hello";</span>
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.

<script type=<span class="hljs-string">"module"</span>>
  <span class="hljs-keyword">import</span> { hello } <span class="hljs-keyword">from</span> <span class="hljs-string">'./hello.mjs'</span>; <span class="hljs-comment">// Or it could be simply `hello.js`</span>
  <span class="hljs-title function_">hello</span>(<span class="hljs-string">'world'</span>);
</script>
<span class="hljs-comment">// hello.mjs -- or it could be simply `hello.js`</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">hello</span>(<span class="hljs-params">text</span>) {
  <span class="hljs-keyword">const</span> div = <span class="hljs-variable language_">document</span>.<span class="hljs-title function_">createElement</span>(<span class="hljs-string">'div'</span>);
  div.<span class="hljs-property">textContent</span> = <span class="hljs-string">`Hello <span class="hljs-subst">${text}</span>`</span>;
  <span class="hljs-variable language_">document</span>.<span class="hljs-property">body</span>.<span class="hljs-title function_">appendChild</span>(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:

<script type=<span class="hljs-string">"module"</span>>
  <span class="hljs-title function_">import</span>(<span class="hljs-string">'hello.mjs'</span>).<span class="hljs-title function_">then</span>(<span class="hljs-function"><span class="hljs-params">module</span> =></span> {
      <span class="hljs-variable language_">module</span>.<span class="hljs-title function_">hello</span>(<span class="hljs-string">'world'</span>);
    });
</script>

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.

<span class="hljs-comment">// mymodule.js</span>
<span class="hljs-variable language_">module</span>.<span class="hljs-property">exports</span> = {
   <span class="hljs-attr">hello</span>: <span class="hljs-keyword">function</span>() {
      <span class="hljs-keyword">return</span> <span class="hljs-string">"Hello"</span>;
   }
}
<span class="hljs-comment">// server.js</span>
<span class="hljs-keyword">const</span> myModule = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./mymodule'</span>);
<span class="hljs-keyword">let</span> val = myModule.<span class="hljs-title function_">hello</span>(); <span class="hljs-comment">// val is "Hello"   </span>

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:

<span class="hljs-title function_">fetchInject</span>([
  <span class="hljs-string">'https://cdn.jsdelivr.net/momentjs/2.17.1/moment.min.js'</span>
]).<span class="hljs-title function_">then</span>(<span class="hljs-function">() =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Finish in less than <span class="hljs-subst">${moment().endOf('year').fromNow(<span class="hljs-literal">true</span>)}</span>`</span>)
})

jQuery Loading

The jQuery library provides loading functionality in one line:

$.<span class="hljs-title function_">getScript</span>(<span class="hljs-string">"my_lovely_script.js"</span>, <span class="hljs-keyword">function</span>() {
   <span class="hljs-title function_">alert</span>(<span class="hljs-string">"Script loaded but not necessarily executed."</span>);
});

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 <script> tag can be injected into either the web page <head>, or inserted just before the closing </body> tag.

Here is an example of how this could work:

<span class="hljs-keyword">function</span> <span class="hljs-title function_">dynamicallyLoadScript</span>(<span class="hljs-params">url</span>) {
    <span class="hljs-keyword">var</span> script = <span class="hljs-variable language_">document</span>.<span class="hljs-title function_">createElement</span>(<span class="hljs-string">"script"</span>);  <span class="hljs-comment">// create a script DOM node</span>
    script.<span class="hljs-property">src</span> = url;  <span class="hljs-comment">// set its src to the provided URL</span>

    <span class="hljs-variable language_">document</span>.<span class="hljs-property">head</span>.<span class="hljs-title function_">appendChild</span>(script);  <span class="hljs-comment">// 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)</span>
}

This function will add a new <script> 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 use your newly loaded code the next line after you asked it to be loaded, because it will be still loading.

For example: my_lovely_script.js contains MySuperObject:

<span class="hljs-keyword">var</span> js = <span class="hljs-variable language_">document</span>.<span class="hljs-title function_">createElement</span>(<span class="hljs-string">"script"</span>);

js.<span class="hljs-property">type</span> = <span class="hljs-string">"text/javascript"</span>;
js.<span class="hljs-property">src</span> = jsFilePath;

<span class="hljs-variable language_">document</span>.<span class="hljs-property">body</span>.<span class="hljs-title function_">appendChild</span>(js);

<span class="hljs-keyword">var</span> s = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MySuperObject</span>();

<span class="hljs-title class_">Error</span> : <span class="hljs-title class_">MySuperObject</span> is <span class="hljs-literal">undefined</span>

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

So what to do about it ?

Well, you can use the hack the author suggests in the link I gave you. In summary, for people in a hurry, he uses an event to run a callback function when the script is loaded. So you can put all the code using the remote library in the callback function. For example:

<span class="hljs-keyword">function</span> <span class="hljs-title function_">loadScript</span>(<span class="hljs-params">url, callback</span>)
{
    <span class="hljs-comment">// Adding the script tag to the head as suggested before</span>
    <span class="hljs-keyword">var</span> head = <span class="hljs-variable language_">document</span>.<span class="hljs-property">head</span>;
    <span class="hljs-keyword">var</span> script = <span class="hljs-variable language_">document</span>.<span class="hljs-title function_">createElement</span>(<span class="hljs-string">'script'</span>);
    script.<span class="hljs-property">type</span> = <span class="hljs-string">'text/javascript'</span>;
    script.<span class="hljs-property">src</span> = url;

    <span class="hljs-comment">// Then bind the event to the callback function.</span>
    <span class="hljs-comment">// There are several events for cross browser compatibility.</span>
    script.<span class="hljs-property">onreadystatechange</span> = callback;
    script.<span class="hljs-property">onload</span> = callback;

    <span class="hljs-comment">// Fire the loading</span>
    head.<span class="hljs-title function_">appendChild</span>(script);
}

Then you write the code you want to use AFTER the script is loaded in a lambda function:

<span class="hljs-keyword">var</span> myPrettyCode = <span class="hljs-keyword">function</span>() {
   <span class="hljs-comment">// Here, do whatever you want</span>
};

Then you run all that:

<span class="hljs-title function_">loadScript</span>(<span class="hljs-string">"my_lovely_script.js"</span>, myPrettyCode);

Note that the script may execute after the DOM has loaded, or before, depending on the browser and whether you included the line script.async = false;. There’s a great article on Javascript loading in general which discusses this.

Source Code Merge/Preprocessing

As mentioned at the top of this answer, many developers use build/transpilation tool(s) like Parcel, Webpack, or Babel in their projects, allowing them to use upcoming JavaScript syntax, provide backward compatibility for older browsers, combine files, minify, perform code splitting etc.

 

ref: https://stackoverflow.com/questions/950087/how-do-i-include-a-javascript-file-in-another-javascript-file