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()
.
Note that the event handler needs to be `async` if you’re using `await` inside it:
button.addEventListener(‘click’, async event => {
Good catch, thanks!