181k views
3 votes
How to include a JavaScript file in another JavaScript file?

User Petebolduc
by
8.7k points

1 Answer

2 votes

Final answer:

To include a JavaScript file in another, use the import statement for modules or dynamically append a script tag to the DOM for non-module scripts.

Step-by-step explanation:

How to Include a JavaScript File in Another JavaScript File

One common way to include a JavaScript file in another JavaScript file is by using the import statement. The import statement allows you to bring in modules, which are reusable pieces of code, from another file. For example, if you have a JavaScript file named 'utils.js' with a function you want to reuse in another file named 'app.js', you can use the following syntax at the top of 'app.js':

import { functionName } from './utils.js';

It’s essential to ensure that the file you are importing from is a module, typically by including 'type="module"' in your HTML script tag when loading the main JavaScript file, or by using a JavaScript bundler like Webpack that handles module loading.

Another method to include files is by using a technique called script loading. You can dynamically create a script tag and append it to the DOM:

var script = document.createElement('script');
script.src = 'path/to/utils.js';
document.head.appendChild(script);

This approach allows you to load scripts on demand and is particularly useful for adding scripts that don't export functionality (e.g., polyfills).

User Jeannot
by
8.5k points