Search code examples
javascriptrequirejsamd

What is the "order!" directive for in this requirejs/amd module?


I'm looking into what appears to be a case of javascript loading out of order in a legacy application. The application uses Require.js to load several modules, and one of our company's modules is executing prior to its dependencies being loaded.

My experience with Require.js and AMDs is very limited, and in researching I noted that in some areas dependencies are prefixed with an order! string, such as:

define(['order!jquery', ...

Whereas in other areas the prefix isn't used:

define(['jquery', ...

So far I can't find documentation of this directive. What's its effect?


Solution

  • Full information copied from here

    Normally RequireJS loads and evaluates scripts in an undetermined order. However, there are some traditional scripts that depend on being loaded in a specific order. For those cases you can use the order plugin. Download the plugin and put it in the same directory as your app's main JS file. Example usage:

    require(["order!one.js", "order!two.js", "order!three.js"], function () {
        //This callback is called after the three scripts finish loading.
    });
    

    Scripts loaded by the order plugin will be fetched asynchronously, but evaluated in the order they are passed to require, so it should still perform better than using script tags in the head of an HTML document.

    The order plugin is best used with traditional scripts. It is not needed for scripts that use define() to define modules. It is possible to mix and match "order!" dependencies with regular dependencies, but only the "order!" ones will be evaluated in relative order to each other.

    Notes:

    • The order! plugin only works with JavaScript files that are cacheable by the browser. If the JS file has headers that do not allow the browser to cache the file, then the order of scripts will not be maintained.
    • Do not use the order! plugin to load other plugin-loaded resources. For instance. 'order!cs!my/coffescript/module' is not recommended. You will get errors in some versions of IE and WebKit. This is due
      to the workarounds the order plugin needs to do for those browsers
      to ensureordered execution.