Thomas K
Thomas K

Reputation: 1117

Require.js Module load order

I have 3 modules : Module A, Module B and Module C.

Module A writes links in my html page (the links come from an ajax async call) Module B writes some links too. In my module C, I would like to add an event on the links from module A and B.

The problem is the module loading order is random. So, when module C is loaded in first, there is no link because Module A and B didn't write yet.

Is there a way to load the module C at the end ?

Thank's

Upvotes: 0

Views: 1994

Answers (1)

Paul Grime
Paul Grime

Reputation: 15104

Module load order should not matter. E.g.

links1.js

define(function() {
    return { addLinks: function() { ... } };
})

links2.js

define(function() {
    return { addLinks: function() { ... } };
})

events.js

define(function() {
    return { addEvents: function() { ... } };
})

app.js

require(["links1", "links2", "events"], function(links1, links2, events) {
    links1.addLinks(...);
    links2.addLinks(...);
    events.addEvents(...);
});

In other words, don't have your modules execute something when they load, have them return methods that can be executed when you are ready.

The modules above can load in any order ...

  • links1, links2, events
  • links1, events, links2
  • links2, links1, events
  • links2, events, links1
  • events, links1, links2
  • events, links2, links1

and it does not matter.


EDIT - If links1 uses XHR, then app needs to wait for those links before adding them.

links1.js

define(function() {
    var promise = null;
    function loadLinks() {
        if (promise) {
            return promise;
        }
        return promise = $.ajax(...).then(function(data) {
            return convertDataToLinks(data);
        });
    }
    return {
        loadLinks: loadLinks,
        addLinks: function() { ... }
    };
})

app.js

require(["links1", "links2", "events"], function(links1, links2, events) {
    links1.loadLinks().then(function(links) {
        links1.addLinks(links);
        links2.addLinks(links);
        events.addEvents(...);
    });
});

Upvotes: 2

Related Questions