简体   繁体   中英

vanilla JS : module bundled or not

Given a set of module-patterned files (a main one, and various subs),

is there a way to detect if modules are bundled together into one single file OR not ? In the last case, I will load manually modules with head script src="" tag added via JS.

Non-bundled files are for development, bundled one is for production use.

EDIT Code is ES 5 !

I don't consider using Browserify, Require or so on...

I assemble my code with (very basic) gulpfiles (using concat, wrap)

someone have an idea ?

Assuming your bundled file has something in the name to indicate that it is the bundle you can check which script is loaded. For example if you load TopModule.js in development mode and TopLevel.min.js in production you can put this detection in the TopLevel module:

var isBundled = (function () {
    var src = '';

    if ('undefined' !== typeof (document.currentScript) && document.currentScript.src) {
        src = document.currentScript.src;
    }
    else {
        (function () {
            var allScriptElements = document.scripts || document.getElementsByTagName('script'),
                    i;

            for (i = 0; i < allScriptElements.length; ++i) {
                if (/(TopLevel(\.min)*)\.js/i.test(allScriptElements[i].src)) {
                    src = allScriptElements[i].src;

                    break;
                }
            }
        }());
    }

    return /\.min\.js/i.test(src);
}());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM