Why does require.js seem to load all my modules when the page loads?

I am developing a single-line core application using requirejs, and today, when I deployed to our beta server, I found that the initial load of the page was about 20 seconds while it was extracting all the scripts.

I assumed that this was because I used an array of dependencies when defining such modules:

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 // ... } } }); 

I figured that when loading the main application module, all other scripts would be loaded due to the fact that each module used this method.

Then I changed the method for selecting modules to get them as needed, calling require('...') directly when I need it:

 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, by launching the application again and checking the Network tab of the Chrome Developer Console, I saw that, as before, the application retrieves all my modules and I get the same page load time.

Have I completely missed this point? Since I had the impression that the scripts would be received on every request. This is not true?

+6
source share
1 answer

To load AMD modules asynchronously, you must call require and provide a function callback that will be called when the requested module is loaded:

 require(['InboxView'], function(InboxView) { // Do something with InboxView here... }); 

The sample code you require('InboxView') is called require('InboxView') in a synchronous style. Since you use sugar syntax, RequireJS will check your code, find any synchronous calls to require() and add these dependencies to the top-level dependency list of the module, giving you the following:

 define(['require', 'InboxView'], function (require) { return Backbone.Router(function () { // ... // route initializtion etc // ... inbox: function (routeVar) { var InboxView = require('InboxView'); this.inboxView = new InboxView(); // render view etc } }); }); 

... therefore, you immediately noticed that all modules are loaded.

Add an asynchronous callback and you should be fine. Also, if you think about it, how will your code work if RequireJS waited for the module to load for InboxView until your route started without blocking the call to require until the download was complete? :)

+6
source

Source: https://habr.com/ru/post/922220/


All Articles