How Do I Include One JavaScript File in Another?
Including one JavaScript file in another is not as straightforward as using @import in CSS. Before ES6, various approaches were utilized to address this issue.
ES6 Modules
Since 2015 (ES6), JavaScript introduced ES6 modules to import modules in Node.js. Most modern browsers also support this standard. ES6 modules use the following syntax:
export function hello() { return "Hello"; }
import { hello } from './module.js'; let val = hello(); // val is "Hello";
Node.js require
Node.js uses the older CJS module style, which is based on the module.exports/require system:
// mymodule.js module.exports = { hello: function() { return "Hello"; } }
// server.js const myModule = require('./mymodule'); let val = myModule.hello(); // val is "Hello"
Other Browser Loading Methods
In addition to ES6 modules, browsers also provide various other options for loading external JavaScript contents:
Detecting Script Execution
When remotely loading code, modern browsers execute scripts asynchronously, so the code may not be available immediately after loading. To detect when the script has been executed, you can use:
The above is the detailed content of How Can I Include One JavaScript File in Another?. For more information, please follow other related articles on the PHP Chinese website!