Alexander Beletsky
Alexander Beletsky

Reputation: 19821

RequireJS loads resources I don't want to

I'm using RequireJS in my app, but don't quite well understand all aspects of it's work.

I have main.js file, where dependencies are described. I have Backbone.Router component up and running, which triggers different application classes (class which is responsible to create main view). Some code you can see here.

What I can see with requireJS: even if some view has not been yet 'required' (mean explicitly call to require('./subviews/view)), it's still loaded and inside it loads all templates (I use requireJS text plugin). If I'm adding new application but it's subviews are not ready, but I never used the application - nonexisting subviews are still loaded and I'm getting 404 errors.

Not sure I explained everything clearly, but hope you got point.

Upvotes: 1

Views: 150

Answers (2)

jrburke
jrburke

Reputation: 6766

Looks like you are using the CommonJS sugared form of define(). Note that this is just a convenience for wrapping Node/CommonJS code, but AMD modules do not operate like Node modules.

An AMD loader will scan for require('') calls in the factory function of the module, and make sure to load all the modules. Otherwise, synchronous access to the that module, by doing a require('./apps/DashboardApp');, would fail in the browser, since file IO is by default async network IO.

If you want to delay loading of some scripts, then you need to use the callback-form of require:

require(['./apps/DashboardApp'], function (DashboardApp) {
});

but this call is an async call, so you would have to adjust your module's public API accordingly.

So basically, if you want to do on-demand loading of a dependency, the callback form of require is needed, given the async nature of file IO in the browser.

Upvotes: 3

Tomas Kirda
Tomas Kirda

Reputation: 8413

Because RequireJS loads all required dependencies. By taking quick look at your code I see that you load routing module and routing has:

var ViewManager = require('ViewManager');

That means it will load ViewManager, dependecies that are specified by ViewManager and other dependencies that those modules need. Essentially when you include require(...), it's the same as specifying dependency. This will be transformed by RequireJS into

define(['ViewManager'], ...)

Upvotes: 1

Related Questions