simonewebdesign

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:

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:

// 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:

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.

View this page on GitHub