How to load jQuery plugins with RequireJS

RequireJS is a useful script loader library. Even if your site/app isn’t super big, it’s usually a good idea to use RequireJS: it makes your code maintainable.

The problem

Often we need to include external plugins that depend on jQuery. Those plugins usually do expect to find a global jQuery ($) object, and then they just extend it.

Of course not all plugins behave like that, but most of them do, and we must deal with it.

By the way, loading jQuery as a global variable is not really a good idea. Okay, you have namespaces, $.noConflict() and IIFEs and whatever but – hey come on, do you really think you need all this stuff? We can do it better.

The solution

Use RequireJS with jQuery to manage dependencies. More specifically, you can use the shim config to specify dependencies for jQuery plugins that are not AMD modules.

Let’s suppose you need to include 2 jQuery plugins, foo.js and bar.js. Here’s a sample configuration:

1
2
3
4
5
6
7
8
9
10
11
requirejs.config({
  shim: {
      foo: {
          deps: ['jquery'],
          exports: 'Foo'
      },
      bar: {
          deps: ['jquery']
      }
  }
});

Then, later, when you need to use that Foo plugin, you can just define a module by doing:

1
2
3
4
5
6
7
8
9
// foo.js
// This defines a module named 'foo'
define(function() {

  var Foo = function() {
      this.bar = 'baz';
  }
  return Foo;
});

And require it when you actually want to execute it:

1
2
3
4
5
require(['foo'], function(Foo) {
  // this is a callback function, and it's optional.
  // the foo module has already been required and executed.
  // Foo and $ are now loaded.
});

Yeah, it’s that simple.

Want to see a working example? Check out the official one.

Comments