Please note, this is a STATIC archive of website www.tutorialrepublic.com from 10 Sep 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
WEB TUTORIALS
PRACTICE EXAMPLES
HTML REFERENCES
CSS REFERENCES
PHP REFERENCES
Advertisements

How to Include a JavaScript File in another JavaScript File

Topic: JavaScript / jQueryPrev|Next

Answer: Use the export and import Statement

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:

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:

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.

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

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

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery Load JS File Demo</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
</head>
<body>
    <script>
    var url = "test.js";
    
    $.getScript(url, function(){
        $(document).ready(function(){
            console.log(str); // Prints: Hi there!
            console.log(num); // Prints: 15
            console.log(multiplyNumbers(4, 25)); // Prints: 100
        });
    });
    </script> 
</body>
</html>

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


Related FAQ

Here are some more FAQ related to this topic:

Advertisements
Bootstrap UI Design Templates