Including JavaScript Files in Other JavaScript Files
In JavaScript, importing modules is different from CSS's @import. Early versions of JavaScript lacked import, include, or require functions, leading to various approaches for including JavaScript files in others. However, since ES6 (2015), JavaScript has introduced the ES6 modules standard to import modules into Node.js and most modern browsers.
ES6 Modules
ES6 modules use the following syntax:
import { function } from './module.js'; // or import * as module from './module.js';
ECMAScript Modules in Browsers
Browsers support ES6 module loading directly, without build tools like Webpack. Use the following syntax:
<script type="module"> import { function } from './module.js'; </script>
Node.js require
Node.js uses the CJS module style:
const module = require('./module.js');
Other Methods
Besides ES6 modules and Node.js require, other ways to include JavaScript files in browsers include:
Detecting Script Execution
Including JavaScript files remotely means asynchronous loading. To ensure that the loaded code is available immediately, use the following technique:
function loadScript(url, callback) { // Create script tag var script = document.createElement('script'); script.type = 'text/javascript'; script.src = url; // Bind event to callback function script.onreadystatechange = callback; script.onload = callback; // Append to HTML document.head.appendChild(script); }
Source Code Merge/Preprocessing
Build tools like Parcel, Webpack, and Babel can be used to merge source codes, provide backward compatibility, and minify files.
The above is the detailed content of How Can I Include JavaScript Files in Other JavaScript Files?. For more information, please follow other related articles on the PHP Chinese website!