##How to use a jQuery Plugin with RequireJS
I'm using several jQuery Plugins for a Node app I'm building. One plugin in particular which I'll use for illustration purposes is jQuery Cookie. jQuery Cookie depends on jQuery, therefore I needed an ascyhonous dependency management solution.
After searching throug RequireJS documentation and trial and error, I was able to put together the following working code to serve as a shim. This code resides in a a file called common.js
and sits at the root of my /javascripts
directory (where all of my other RequireJS modules camp out as well.) In this file I define two resources. In this case I'm pointing to CDN versions of jQuery and jQuery Cookie (this actually further exaserbates the need for a dependency management system as I'm not loading these resources from my own server and can't control latency and network delays.)
common.js
require.config({
paths: {
// No .js filename extension necessary, RequireJS adds it
'jquery': '//cdnjs.cloudflare.com/ajax/libs/jquery/2.0.3/jquery.min',
'cookie': '//cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.0/jquery.cookie.min'
},
shim: {
'jquery': { exports: '$' }, // makes the global $ object available in the window context
'cookie': { deps: ['jquery'] }
}
});
home.js - This file is my app initializer, which is standard practice when using RequireJS. I pass in common
as a dependency which we just defined above. The themeSwitcher()
function is another module I pass in, which also happens to depend on jQuery.
require(['common', 'themeswitcher'], function(themeSwitcher) {
themeSwitcher('blueTheme');
});
Here are network requests for jQuery and jQuery Cookie, respectively. As you can see jQuery Cookie asychonously loads AFTER jQuery is finished loading: