How to achieve lazy loading with RequireJS?

Is this actually possible? Are there black magicks in RequireJS that looks for calls to require() without actually triggering the doStuff route?

When you use the 'sugar' syntax it uses Function.prototype.toString and a regex to extract your references to require and then lists them as dependencies before running the function. Basically it becomes the normal style of define with an array of deps as the first argument.

Because of this, it doesn't care where your require calls are and that's why conditional statements are ignored (it also explains why those require calls have to use a string literal, and not a variable).

Is this the theoretically correct way of going about 'on-demand', lazy loading of RequireJS modules and resources?

Using the sugar syntax won't allow conditional loading as you've seen. The only way I can think of off the top of my head is to use a require call with an array of deps and a callback:

define(function(require) {
    var module1 = require('module1');

    // This will only load if the condition is true
    if (true) {
        require(['module2'], function(module2) {

        });
    }

    return {};
});

Only downside is another nested function but if you're after performance then this is a valid route.

Does the r.js optimizer still work as advertised if you use this notation?

If you're using the 'sugar' syntax then yes, the optimiser will work fine. An example:

modules/test.js

define(function(require) {
    var $ = require('jquery');
    var _ = require('underscore');

    return {
        bla: true
    }
});

Once compiled by r.js this looks like:

define('modules/test', ['require', 'jquery', 'underscore'], function(require) {
    var $ = require('jquery');
    var _ = require('underscore');

    return {
        bla: true
    }
});

In conclusion you can load stuff conditionally, but as you mentioned, if you intend to optimise the project with r.js then there isn't a huge overhead in just using the sugar syntax.


You may also want to check out require-lazy.

It has a runtime component and a build time component. The runtime component allows you to lazily require a module as (note the lazy! plugin):

define(["lazy!mymodule"], function(mymodule) {
    ...
});

In the previous context, mymodule is a promise, the real module will be loaded with get() and will be made available in the then() callback:

mymodule.get().then(function(m) {
    // here m is the real mymodule
});

Require-lazy integrates with r.js to automatically create "bundles" of Javascript files. It also handles automatically cache-busting for the bundles. There are several examples to get an idea. There is also Grunt and Bower integration.