Creating a loading sequence of an application I am using Webpack to create a sort of loading sequence of the application. I can simply call prepareInfosite().render() and I don't need to care about the hidden async nature of it.

export function prepareInfosite() {
    return setupRenderer((resolve) =&gt; {
        require.ensure(['./infosite'], (require) =&gt; resolve(require('./infosite')), 'infosite');
    });
}

export function prepareLoading() {...}
export function prepareGame() {...}

const uiContainerElement = document.createElement('div');
document.body.appendChild(uiContainerElement);

function setupRenderer(resolver) {
    let uiModule = null;
    let rendered = false;
    const renderArgs = [uiContainerElement];

    function executeRender() {
        if (rendered === true &amp;&amp; uiModule !== null) {
            uiModule.render(...renderArgs);
        }
    }

    resolver((resolvedUiModule) =&gt; {
        uiModule = resolvedUiModule;
        executeRender();
    });

    return {
        render(...args) {
            rendered = true;
            renderArgs.push(...args);
            executeRender();
        },
    };
}


Originally, the setupRenderer looked like this, but since I am using Babel, it has polyfilled the Promise and size has grown from like 6kB to 22kB (after uglify2!), which isn't very nice.

function setupRenderer(resolver) {
    const promise = new Promise(resolver);
    return {
        render(...args) {
            promise.then((uiModule) =&gt; uiModule.render(uiContainerElement, ...args));
        },
    };
}


Do you think there is a nicer way how to express this without any external dependency?

Additionally, I would like to DRY up the lines with require.ensure. I am not entirely sure how this works, but is there some way how to specify name of loaded file dynamically, perhaps using context?
Do you think there is a nicer way how to express this without any external dependency?


Use Babel preset to only include browsers from the last two years. In that case, the promise polyfill is not needed. For example

{
  "presets": [
    ["env", {
      "targets": {
        "browsers": ["since 2016"]
      }
    }]
  ]
}



  Additionally, I would like to DRY up the lines with require.ensure. I am not entirely sure how this works, but is there some way how to specify name of loaded file dynamically, perhaps using context?


Use a wrapper function to pass the strings as arguments:

return setupRenderer((resolve) =&gt; { ensurance('./infosite', 'infosite')});


And define the function before the call:

function ensurance(path, name){
  require.ensure([path], (require) =&gt; resolve(require(path)), name);
}


References


Babel: env preset
caniuse: promises