JAVASCRIPT

Dynamic Module Import

This example loads a module dynamically when the url has a view=alt query string parameter. e.g., ?view=alt.

modules/alt-view.js
export default function() {
    const css = `
        @media (min-width: 768px) {
            h1 { background: red; }
        }
    `;

    let head = document.head;
    let style = document.createElement('style');

    head.appendChild(style);
    style.appendChild(document.createTextNode(css));
}

Source

let url = window.location.href;

function hasQueryString(url) {
    // regex pattern for detecting querystring
    var pattern = new RegExp(/\?.+=.*/g);
    return pattern.test(url);
}

if (hasQueryString(url)) {
    let params = (new URL(document.location)).searchParams;
    let view = params.get("view");
    console.log(view)

    if (view == 'alt') {
        /**
         * using promise */
        import('./modules/alt-view.js')
        .then((module) => {
            module.default();
        }).catch(err => {
            console.log(err.message);
        });

        /**
         * using async await */
        // (async () => {
        //     const module = await import('./modules/alt-view.js');
        //     module.default();
        // })();
    }

}

reference

comments powered by Disqus