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.
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.
Let’s suppose you need to include 2 jQuery plugins,
bar.js. Here’s a sample configuration:
Then, later, when you need to use that
Foo plugin, you can just define a module by doing:
And require it when you actually want to execute it:
Yeah, it’s that simple.
Want to see a working example? Check out the official one.