jQuery Load JS File Demo

How to Include a JavaScript File in another JavaScript File

Since ECMAScript 6 (or ES6) you can use the export or import statement in a JavaScript file to export or import variables, functions, classes or any other entity to/from other JS files.

For example, let’s suppose you’ve two JavaScript files named «main.js» and «app.js» and you want to export some variables and functions from «main.js» to «app.js». Then in «main.js» file you need to write the export statement (line no-9) as shown in the following example:

Example

let msg = "Hello World!"; const PI = 3.14; function addNumbers(a, b) < return a + b; >// Exporting variables and functions export < msg, PI, addNumbers >;

And in «app.js» file you need to write the import statement (line no-1) as shown here:

Example

import < msg, PI, addNumbers >from './main.js'; console.log(msg); // Prints: Hello World! console.log(PI); // Prints: 3.14 console.log(addNumbers(5, 16)); // Prints: 21

Alternatively, you can use the jQuery getScript() method to load a JS file from the server, then execute it with a sigle line of code. Let’s suppose you have a JS file «test.js» with the following code.

Example

// Defining variables var str = "Hi there!"; var num = 15; // Defining a function function multiplyNumbers(a, b)

Now you can load this «test.js» file in your script using the getScript() method, like this:

Example

          

See the tutorial on JavaScript ES6 features to learn about the new features introduced in ES6.

Here are some more FAQ related to this topic:

Источник

How to include a JavaScript file in another JavaScript file?

Javascript Course - Mastering the Fundamentals

We can include a JavaScript file in another JavaScript file using the native ES6 module system. This allows us to share code between different JavaScript files and achieve modularity in the code. There are other ways to include a JS file like Node JS require , jQuery’s getScript function, and Fetch Loading.
In this article, we are going to go through each method in detail.

What are ES6 Modules?

In the early era of the web, the role of JavaScript was limited to form validation and providing a little bit of interactivity, so large scripts were not needed.

Today, JavaScript has become a primary language to develop web apps, including both backend and frontend. Thus the size of the JS programs has also grown exponentially, making it harder to manage code.

Читайте также:  Java exception error messages

This motivated the use of module system, a way to divide the code into multiple files and directories but still make sure all the bits of code can access one another.

As the old versions of JavaScript have no native module system, many JavaScript libraries come with their own. For example — CommonJS and RequireJS.

JavaScript introduced a native module system in ES6 (ECMAScript 6 — the official name of JavaScript) called the ES6 Module.

An ES6 module is just a file containing JS code with two special characteristics:

  • It is automatically in strict-mode: this prohibits the use of sloppy mistakes in the code, like using variables without defining.
  • You can use the import or export keyword inside of it: providing a way to share the code with other files.

Let’s discuss different ways to achieve modularity and learn how to import a JS file into a JS file.

An ES6 module is a JS file that can export its code to share with other files and import and use code from other JS files.

In this section, we will learn about two popular ways of including a JS file in another JS file:

Using import/export | ES6 module

Let’s start by using the ES6 way of importing and exporting. Create a file named utils.js and define the following function and constant inside it:

Notice that we used the export keyword before the function and variable to specify that these objects can be used by other files.

The Hello, $ is a template literal in JavaScript. It allows us to embed variables inside a string using the $ and <> syntax.

Now, create another file named main.js and write the following code in it:

syntax to import

In the first line, we are importing greet and message from utils.js by specifying them inside of curly braces <> .
After this line, we can use the imported objects as they are defined in the same file. Then, we console logged the output of both the objects.

ES6 syntax for importing: import from ‘filename.js’

If you are going to use ES6 modules in a node js environment, remember to name your files with .mjs extension or set «type»: «module» in the package.json file.

Using Default Exports

We can use the default keyword to export one object by default from a file. What does this mean? Let’s see with an example. Make the greet function in utils.js a default export by adding default before it:

Now, you can import it in main.js like this:

It will work the same as before!

While performing default export, randomName is imported from greet.js. Since randomName is not in utils.js , the default export ( greet() in this case) is exported as random_name.

Читайте также:  Php ajax error response

Let’s discuss some important points related to ES6 modules that one should remember when using them:

    We have to remove the curly braces when importing default exports.
    For instance, if we have kept the braces in the randomName example above like this:

Источник

Ways to include a JavaScript file in another JavaScript file

How can you reliably and dynamically load a JavaScript file? This will can be used to implement a module or component that when ‘initialized’ the component will dynamically load all needed JavaScript library scripts on demand. 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 and/or transpilation tools can be used.

ES6 Modules

ECMAScript (ES6) modules have been supported in Node.js since v8.5, with the —experimental-modules flag. All files involved must have the .mjs extension.

// module.mjs export function hello()
// main.mjs import < hello >from 'module'; // or './module' 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.

  
// hello.mjs export function hello(text) < const div = document.createElement('div'); div.textContent = `Hello $`; document.body.appendChild(div); >

Dynamic imports in browsers

Dynamic imports let the script load other scripts as needed:

Node.js require

The old style of importing modules, still widely used in Node.js, is the module.exports/require system.

// server.js const index = require('./index'); let val = index.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 $`) >)

jQuery Loading

The jQuery library provides loading functionality in one line:

$.getScript("my_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.

Читайте также:  Найти позицию подстроки php

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

For example: my_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! 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:

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 head.appendChild(script); >

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

var myPrettyCode = function() < // Here, do whatever you want >;
loadScript("my_script.js", 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; .

Источник

Оцените статью