Search code examples
jqueryjs-amd

Is this jQuery AMD syntax?


Recently, I can see all the jQuery plugins start with the below line.

function (factory) {
    if (typeof define === 'function' && define.amd) {
        // AMD
        define(['jquery'], factory);
    } else if (typeof exports === 'object') {
        // CommonJS
        module.exports = factory;
    } else {
        // Browser globals
        factory(jQuery);
    }
}(function ($) {}));

I think it to be a similar concpet like Require.js, but I am not very sure. Can someone tell me what is this called or how it works? So that I can learn more on this.

PS: Please feel free to modify the Title of the question or mark it duplicate if we have it already in SO.


Solution

  • You are quite correct.

    If we need to achieve AMD then we are inclined towards Require.js, but what if we want to achieve the same without Require.js? Then we would land up to the syntax mentioned by you. Which is called as UMD : Universal Module Definition

    From the source:

    jqueryPlugin.js - Defines a jQuery plugin that works with AMD and browser globals.

    jqueryPluginCommonjs.js - Defines a jQuery plugin that works with AMD and browser globals, but also in a CommonJS environment. Use this version if you are running jQuery (or the jquip or jquery-untouched projects) in a CommonJS environment that can load jQuery appropriately.