Requirejs why and when to use shim config

A primary use of shim is with libraries that don’t support AMD, but you need to manage their dependencies. For example, in the Backbone and Underscore example above: you know that Backbone requires Underscore, so suppose you wrote your code like this:

require(['underscore', 'backbone']
, function( Underscore, Backbone ) {

    // do something with Backbone

}

RequireJS will kick off asynchronous requests for both Underscore and Backbone, but you don’t know which one will come back first so it’s possible that Backbone would try to do something with Underscore before it’s loaded.

NOTE: this underscore/backbone example was written before both those libraries supported AMD. But the principle holds true for any libraries today that don’t support AMD.

The “init” hook lets you do other advanced things, e.g. if a library would normally export two different things into the global namespace but you want to redefine them under a single namespace. Or, maybe you want to do some monkey patching on a methods in the library that you’re loading.

More background:

Leave a Comment