UPDATE June 2019: This feature has now advanced to Stage-4 and will be part of the ES2020 Specification! 🎉
One of the recent ECMAScript proposals that landed in Chrome 63 is dynamic import()
:
Dynamic
import()
introduces a new function-like form ofimport
, which allows one to import on demand. It returns a promise for the module namespace object of the requested module, which is created after fetching, instantiating, and evaluating all of the module’s dependencies, as well as the module itself.
Say you have a lightbox or dialogbox. You could offload its importing to the very moment it is needed:
button.addEventListener('click', async (event) => {
try {
const dialogBox = await import('./dialogBox.mjs');
dialogBox.open(…);
} catch (error) {
// …
}
});
Note that we’re using await
here, as it’s better than the typical promise code which uses .then()
.
The proposal is currently Stage-3
💁♂️ Stage-3?
The Technical Committee which is concerned with the standardization of ECMAScript (i.e. TC39) has a 5 stage process in place, ranging from stage-0 to stage-4, by which it develops a new language feature.
Stage-3 is the Candidate Stage where the feature is considered complete and only critical changes will happen based on implementation experience. If all goes well the proposal will advance to Stage 4 without any changes, after which it will to become part of the ECMAScript Specification.
Note that the event handler needs to be `async` if you’re using `await` inside it:
button.addEventListener(‘click’, async event => {
Good catch, thanks!