This is a common library pattern we see today and at first it struck me as odd. It took a while to understand what was happening.
First, This is a self executing function that passes in a function. Let's first look at the construct before we look at the actions.
// Self executing function that takes no arguments.
(function () {
// Some code here.
})();
// Self executing function that takes an argument.
(function (argument) {
alert(argument);
})("Hello World");
// Self executing function that takes function as argument.
(function (factory) {
// Self executing. Executes as soon as the script is loaded.
// At this point, factory = the function below.
})(function (param) {
// Not self executing! Must be called.
});
Now that we understand the construct of what is happening here, let's look at this code:
// If there is a variable called "define", and that variable is a function, call that function with the paramenter jQuery and pass it the function. This is how we define a library in RequireJS.
if ( typeof define === "function" && define.amd ) {
define( ["jquery"], factory );
} else {
// This is how we define the jQuery library everywhere else in the world. We pass the global window.jQuery into the function.
factory( jQuery );
}
So all together now,
// Define jQuery.
(function (factory) {
// If using RequireJS, define jQuery by calling the define function with the jQuery factory.
if ( typeof define === "function" && define.amd ) {
define( ["jquery"], factory );
} else {
// Otherwise, just call the jQuery factory.
factory( jQuery );
}
}(function ($) {
// Use JQuery or $.
});