Including files/modules into your project that located locally on your server is pretty straight forward right? But how do we require a file hosted on a CDN?
What is an AMD module?
First of all the Javascript module you are requiring must be AMD compliant, what the hell does that mean right? Well AMD stands for Asyncronous Module Definition. It is a sort of standard for defining modules that can be loaded into module loaders such as RequireJS. In short it means that within the module define() must be called.
What the jQuery AMD module definition looks like:
if ( typeof define === "function" && define.amd && define.amd.jQuery ) {
define( "jquery", [], function () { return jQuery; } );
}
What jQuery Says:
“Expose jQuery as an AMD module, but only for AMD loaders that understand the issues with loading multiple versions of jQuery in a page that all might call define(). The loader will indicate they have special allowances for multiple jQuery versions by specifying define.amd.jQuery = true. Register as a named module, since jQuery can be concatenated with other files that may use define, but not use a proper concatenation script that understands anonymous AMD modules. A named AMD is safest and most robust way to register. Lowercase jquery is used because AMD module names are derived from file names, and jQuery is normally delivered in a lowercase file name.”
How can we take advantage of this in RequireJS?
Below is an example of how to include jQuery and Underscore, two AMD compliant libraries that both contain the special define() module definition. View the source of both libraries and search the page for ‘define(’ to see where they have been defined and with what name.
require.config({
paths:{
'jquery': 'http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.min',
'underscore': 'https://raw.github.com/documentcloud/underscore/master/underscore'
}
});
require([
'jquery',
'underscore'
], function($, _) {
// log jQuery to console to make sure it is available
console.log($);
// log underscore to console to make sure it is available
console.log(_);
});
Example Demo:
Important things to note:
define() module definition cannot be included into your project in this way.