Question

When multiple JavaScript modules are define()'d using AMD and concatenated into a single file, are those modules still considered asynchronous?

Was it helpful?

Solution 2

Yes, they are still considered async.

While the module itself doesn't have to be loaded from disk, the modules do need to be executed and there is a call back made.

Because you can combine SOME modules into a single file doesn't mean you have to combine all -- nor does RequireJS assume all there.

It will run what it can from your preload and async load the rest.

OTHER TIPS

Generally speaking, just concatenating a bunch of AMD modules together won't make them synchronous. However, if you can live with additional limitations and select a loader that can do it, you can load AMD modules synchronously.

RequireJS

I don't know of a case where RequireJS will load anything synchronously, even if asynchronous loading is not needed. You could have the following in a <script> tag:

define("foo", [], function () {
});

require(["foo"], function (foo) {
});

There is nothing to load here because all the code is already present there. The foo module does not need to be fetched from anywhere. It's list of dependencies is known, etc. Yet, RequireJS will handle it asynchronously.

One source of confusion for some wondering about RequireJS' capability to load modules synchronously could be RequireJS' synchronous form of require. You can do:

define(function(require) {
    var foo = require("foo");
});

The call to require here looks like it is synchronous but RequireJS transforms it behind the scenes into this, by adding "foo" to the list of define's required modules:

define(["foo"], function(require) {
    var foo = require("foo");
});

So while the require call looks synchronous, RequireJS still handles it asynchronously.

Almond

Almond is a loader made by James Burke, who is also the author of RequireJS, that can load AMD modules synchronously. Now, Almond comes with a series of limitations. One such limitation is that you can't load anything dynamically. That is, the entire list of modules you want to load has to be part of the optimized bundle you create with r.js and give to almond for loading. If you can live with the limitations of almond, then it is quite possible to load a bunch of AMD modules synchronously. I've provided details on how to do this in this answer.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top