How to include JS file to another JS file?

Tine JavaScript tutorial on a sophisticated topic with code examples
30 August 2017   158174

Hype.codes team made a research and found several ways to solve this issue.

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

But recent versions of JavaScript have standards like ES6 modules to import modules, although this is not supported yet by most browsers. Many people using modules with browser applications use build and/or transpilation tools to make it practical to use new syntax with features like modules.

ES6 Modules

Note that currently, browser support for ES6 Modules is not particularly great, but it is on it's way. They are supported (but behind flags) in Chrome 60, Firefox 54 and MS Edge 15, with only Safari 10.1 providing support without flags.

Thus, you will currently still need to use build and/or transpilation tools to valid JavaScript that will run in without any requirement for the user to use those browser versions or enable any flags.

Once ES6 Modules are commonplace, here is how you would go about using them:

// module.js
export function hello() {
  return "Hello";
}

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

Node.js

Node.js is currently using a module.exports/require system. You can use babel to transpile if you want the import syntax.

// mymodule.js
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.

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 <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:

function dynamicallyLoadScript(url) {
    var script = document.createElement("script"); //Make a script DOM node
    script.src = url; //Set it's 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 <script> tag to end of the head section of the page, where the srcattribute 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.

How to detect executed script?

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:

var js = document.createElement("script");

js.type = "text/javascript";
js.src = jsFilePath;

document.body.appendChild(js);

var s = new MySuperObject();

Error : MySuperObject is undefined

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

Frontend News Digest 12 - 18.10

Building command line spinners in Node.js, perfect architecure for your next node project and Zero update in this issue Frontend News Digest
18 October 2019   111

Greetings! I hope your week went great! Here's new Frontend news digest.

Another version of a super popular Node.js relaesed, get the info bellow! Also, you will be able learn about Firefox new websocket inspector, WordPress update and watch the video how to built classic layout fast in CSS grid

Guides

  • Build Command-Line Spinners in Node.js

CLI spinners creating will improve your Node.js terminal skills

Articles

  • Improving Form Controls in Microsoft Edge and Chromium 

The Chrome and Edge teams worked together on refreshing form controls in Chromium-based browsers; learn what they have made

  • Firefox’s New WebSocket Inspector

Overview of new Firefox's websocket inspector, which is going to be released in Firefox 71 but availbale only in Firefox Developer Edition at the moment.

  • The Perfect Architecture Flow for Your Next Node Project 

Best practices and architectural tips for your next Node project

  • Coloring Your Terminal Using Nodejs

Article on how coloring libraries like Chalk work under the hood.

Updates

  • WordPress 5.2.4 Release Addresses Several Security Issues

Information about security fixes the news WordPress release

  • Node v12.12.0 (Current)

Another update of the the popular JS RTE with some interesting changes, such as a --force-context-aware flag has been added to prevent addons that aren’t context aware from being loaded, the fs module has added opendir() and fs.Dir as ways to asynchronously iterate through directories and JSON module support has also been made experimental again, due to security concerns in the Web-based implementation of the idea.

  • Zero

A graphics pipeline implemented in JavaScript and rendered to the terminal that can run without GPU required.

Video

Build a Classic Layout FAST in CSS Grid

Podcast

  • Jen Simmons on Browser Features 

Discussion between Jen Simmons, designer advocate at Mozilla and two hosts, Dave Rupert and Chris Coyier. about how new features get shipped to browsers, and how you can get your ideas over to browser makers for consideration.