Search code examples
jquerybackbone.jsrequirejsjs-amd

Requirejs - Loading modules only if a condition is true


Using Requirejs, how can I load modules only if a condition is true? example, If the user is Admin, load file the module a.js.

PS: I'm using Backbone with Requirejs.


Solution

  • Something like this?

    define([], function () {
        function realWork (modulea) {
            // do stuff ...
            // so stuff with modulea
            if (modulea) {
                ...
            }
        }
    
        if (isAdmin) {
            require(["modulea"], function (modulea) {
                realWork(modulea);
            });
        } else {
            realWork();
        }
    });
    

    You might be able to write your own requirejs plugin to tidy this up if you find yourself repeating the pattern.