After struggling for months with RequireJS 2.0 and why it seemed to ignore our dependencies for ordered script loading, we finally found the issue today and it was a facepalmableteachable moment. When setting up a module to use something like SignalR, jQuery must be loaded first. Searches quickly led to StackOverflow posts that suggested configuring dependency shims in RequireJS with something like:
require.config({
shims: {
‘signalr’: [‘jquery’],
‘backbone’: [‘jquery’],
}
}
In theory, when later requiring ‘signalr’, RequireJS will see that it needs to load ‘jquery’ first and all is well:
define([‘signalr’], function() {
return {
initialize: function() { $.connection.doSomething; }
};
});
In practice, what we (and many others, based on the abundance of posts) saw was that SignalR complained about needing jQuery loaded first. In fact, Developer Tools showed that not only was the request for jQuery not being prioritized before SignalR, but it wasn’t being requested at all.
Maybe Dependencies Don’t Autoload?
A quick check of the RequireJS API confirms that this should be working. Some more searches lead to StackOverflow posts where others are inexplicably having similar problems with dependencies. My first logical guess was that RequireJS doesn’t automatically load specified dependencies for you, but rather it just orders them correctly while still requiring you to specify every dependency. This seemed to defeat the purpose of RequireJS, but what the heck. I tried adding ‘jquery’ in to our define:
define([‘jquery’, ‘signalr’], function() {
return {
initialize: function() { $.connection.doSomething; }
};
});
Face, meet palm
shim: {
‘signalr’: [‘jquery’],
‘backbone’: [‘jquery’],
}
}