Dynamically import ES modules with “dynamic import()

One of the recent ECMAScript proposals that landed in Chrome 63 is dynamic import():

Dynamic import() introduces a new function-like form of import, 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().

Google Developers: Dynamic import()

Elsewhere , ,

3 Responses to Dynamically import ES modules with “dynamic import()

  1. Šime Vidas says:

    Note that the event handler needs to be `async` if you’re using `await` inside it:

    button.addEventListener(‘click’, async event => {

  2. Pingback: Customizing Pull-to-Refresh and Overflow Effects with CSS’ overscroll-behavior | Bram.us

Leave a Reply

Your email address will not be published. Required fields are marked *