Q:

How to Include a JavaScript File in another JavaScript File

0

How to Include a JavaScript File in another JavaScript File

All Answers

need an explanation for this answer? contact us directly to get an explanation for this 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>

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

JavaScript / jQuery Frequently Asked Questions

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
How to Detect Screen Resolution with JavaScript... >>
<< How to Get the Current URL with JavaScript...