Search code examples
javascriptdojoamdlegacy-code

How can I load non-AMD dependencies in the defined order with dojo?


I try to make a non-AMD library loadable with dojo, I've chosen a separate folder as a new (pseudo) AMD-package and placed the files of that library in that folder, together with the main.js file, which will get loaded by convention by the dojo loader when the package is requested. In this main.js file I simply put the names of my library files in the dependency list of the define() call.

define([
    "jquery", 
    "./lib/jquery-ui/jquery-ui.min",
    "./the.actual.library.that.uses.the.others",
], function () {
    return window.someGlobalSetByTheLibrary;
});

The problem with this is: the loading order of that dependencies depends on the network latency, it is not guaranteed to be the order they appear in the define().

That causes (sometimes) an error because the actual library file needs its own dependencies to be loaded first.


Solution

  • Dojo has a perfect means to help yourself: loader plugins.

    You can write your own sequential loading plugin that ensures the loading order for you.

    (For copyright reasons of corporate owned code I can not post the implementation here, but it's quite easy using dojo's Deferred and Promise to chain one loading request after the other, internally using require() to do the actual loading).

    Let's assume, your dojo loader plugin has the module id myPackage/sequentialLoading. Then, your main.js will look like this.

    define([
        "myPackage/sequentialLoading!jquery",
        "myPackage/sequentialLoading!./lib/jquery-ui/jquery-ui.min",
        "myPackage/sequentialLoading!./the.actual.library.that.uses.the.others",
    ], function () {
        return window.someGlobalSetByTheLibrary;
    });