Why does require.js seem to be loading all my modules on initial page load?

Viewed 1477

I am developing a single page backbone app using requirejs, and today when I deployed to our beta server, I discovered that the initial page load was around 20 seconds while it fetched all the scripts.

I assumed this was because I was using the dependency array when defining modules like so:

define([
    'ui',
    'models/user',
    'collections/campaigns',
    'collections/groups',
    'collections/keywords',
    'collections/inboxes',
    'collections/templates',
    'collections/contacts',
    'router'
], function (Ui, UserDetails, Campaigns, Groups, Keywords, Inboxes, Templates, Contacts, Router) {

    return {
        start: function () {
            // ...
            // initialize and start app
            // ...
        }
    }
});

Which I believed meant that when the main application module was loaded, every other script would be loaded, due to the fact that every single module was using this method.

I then changed the method of fetching modules to get them as I needed them by calling require('...') directly when I need them like this:

define(function (require) {
    return Backbone.Router(function () {
        // ...
        // route initializtion etc
        // ...

        inbox: function (routeVar) {
            var InboxView = require('InboxView');
            this.inboxView = new InboxView();
            // render view etc
        }
    });
});

However to my surprise, upon running the app again and checking the network tab of chromes developer console - I saw that as before the application is fetching all of my modules, and I am getting the same page load time.

Am I completely missing the point here? As I was under the impression that the scripts would be fetched upon each call of require. Is that not right?

1 Answers
Related