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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)