During the development of my single-page backbone app using requirejs, I encountered an issue when deploying to our beta server. The initial page load took around 20 seconds as it had to fetch all the necessary scripts.
I initially believed that this delay was due to using a 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
// ...
}
}
});
This approach made me believe that all scripts would be loaded when the main application module was loaded, causing the slow initial load time.
Trying to optimize, I switched to dynamically fetching modules by calling require('...')
directly when needed, like this:
define(function (require) {
return Backbone.Router(function () {
// ...
// route initialization etc
// ...
inbox: function (routeVar) {
var InboxView = require('InboxView');
this.inboxView = new InboxView();
// render view etc
}
});
});
To my surprise, even after making this change and running the app again, I found that all modules were still being fetched during the initial load, resulting in the same delay.
Am I missing something here? I thought that scripts would be fetched only when required, but it seems not to be the case. Can someone clarify this for me?