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');
    } 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()

Join the Conversation


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

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

Leave a comment

Leave a Reply to Bramus! Cancel reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.