Using RequireJS and jQuery

Skill Level: 
Intermediate

The UNLedu framework uses a tool called RequireJS to load javascript libraries and dependencies. This guide will walk you through some RequireJS basics, including how to load javascript dependencies safely. At first glance, this might seem needlessly complex, but it is actually pretty simple. RequireJS has some great documentation on how to use it. We won't dive into the details here, only the basics.

Loading jQuery

Simply use the require function. The first parameter should be an array of dependencies, and the second parameter should be an anonymous function to run after the dependencies have loaded. The parameters for the anonymous function are mapped to the first parameter of the require function.

require(['jquery'], function($) {
    //place any code that relies on $ here
});

Loading multiple and custom libraries

See the loading jQuery example for details on how the require function works

require(['absolute path to library', 'jquery'], function(loadedLib, $) {
    //place any code that relies on $ and loadedLib here
});

Configuring RequireJS

So now that you're convinced that RequireJS is awesome, let's cover how to configure it to work with your dependencies that are not a part of the framework. By default, we set the baseUrl configuration value to the base JavaScript directory for framework bundled dependencies. It should be no surprise that this won't work for module dependencies that you want to host in your own directory structure. To work around this, you should set a paths configuration value for each local dependency.

require.config({
    paths: {
    "local-module-name": "url/to/local-module-name"
    }
});

If your website or project has a lot of javascript dependencies, it might be worth configuring RequireJS to search certain paths on your server for the correct javascript file. See the RequireJS documentation for details on how to accomplish this.

Dealing with dependencies that are not AMD loader friendly/ready

While many JavaScript plugins and modules are adopting AMD loaders, there is a chance you will come across something that still uses the old way of relying on variables in the global scope. We've prepared a common jQuery dependency wrapper that can be put around these scripts so they work with the module loader.

header:

(function(factory) {
    if (typeof define === 'function' && define.amd) {
    // AMD
    define(['jquery'], factory);
    } else if (typeof module === 'object' && module.exports) {
    factory(require('jquery'));
    } else {
    // Browser globals
    factory(jQuery);
    }
}(function(jQuery) {
footer:
}));
Contributed By: 
IIM