Blog // Injecting jQuery Into a UMD IIFE

By Destin Moulton on April 23, 2015


    A few weeks ago I did a blog post on a handy JavaScript pattern called Universal Module Definitions (UMDs). The UMD pattern is a great way to provide an IIFE that is compatible with AMD, CommonJS (node), or the browser.


    To utilize an external object in a namespace-safe fashion, the UMD conditional needs to be amended. For instance, to use jQuery with node, the require('jquery') function should be called as the app's parameter.

    Here is a simple version of jQuery being injected into a UMD.

    (function(global, appName, app){
        // Universal Module Definition with jQuery
        if (typeof define === 'function' && typeof define.amd  === 'object'){
            // RequireJS
            define(['jquery'], app);
        } else if (typeof module !== 'undefined'){
            // Export as a node or CommonJS module
            module.exports = app(require('jquery'));
        } else {
            // Add the app to the global browser namespace
            global[appName] = app(global.jQuery);
    })(this, 'App', function($){
        "use strict";
        // Define the IIFE encapsulate methods here
        // ...
        // Return the methods that you want to be publicly accessible
        return {