# How to use RequireJS with jQuery

- Get RequireJS§ 1
- Set up your HTML page§ 2
- Feel the need for speed§ 3
- Advanced use§ 4

When a project reaches a certain size, managing the script modules for a project starts to get tricky. You need to be sure to sequence the scripts in the right order, and you need to start seriously thinking about combining scripts together into a bundle for deployment, so that only one or a very small number of requests are made to load the scripts.

You may also want to load code on the fly, after page load.

RequireJS can help you manage the script modules, load them in the right order, and make it easy to combine the scripts later via the RequireJS optimizer without needing to change your markup. It also gives you an easy way to load scripts after the page has loaded, allowing you to spread out the download size over time.

RequireJS has a module system that lets you define well-scoped modules, but you do not have to follow that system to get the benefits of dependency management and build-time optimizations. Over time, if you start to create more modular code that needs to be reused in a few places, the module format for RequireJS makes it easy to write encapsulated code that can be loaded on the fly. It can grow with you, particularly if you want to incorporate internationalization (i18n) string bundles, to localize your project for different languages, or load some HTML strings and make sure those strings are available before executing code, or even use JSONP services as dependencies.

## Get RequireJS § 1

First step is to get RequireJS:

- download the sample project.

This sample project uses a combined jQuery+RequireJS file. If you prefer to not bundle jQuery with RequireJS, the sample project's README has an alternate way to use jQuery with RequireJS, but it requires consideration of more edge cases.

## Set up your HTML page § 2

A sample HTML page would look like this (assuming you put all your .js files in a "scripts" subdirectory):

    <!DOCTYPE html>
    <html>
        <head>
            <title>jQuery+RequireJS Sample Page</title>
            <script data-main="scripts/main" src="scripts/require-jquery.js"></script>
        </head>
        <body>
            <h1>jQuery+RequireJS Sample Page</h1>
        </body>
    </html>

The path rules used for data-main changed in RequireJS 0.23. Before that version, data-main="main" for the above example.

The data-main attribute on the script tag for require.js tells RequireJS to load the scripts/main.js file. RequireJS will load any dependency that is passed to require() without a ".js" file from the same directory as the one used for data-main. If you feel more comfortable specifying the whole path, you can also do the following:

    <script data-main="scripts/main.js" src="scripts/require-jquery.js"></script>

What is in main.js? A call to require() to load all the scripts you need and any init work you want to do for the page. This example main.js script loads two plugins, jquery.alpha.js and jquery.beta.js (not the names of real plugins, just an example). The plugins should be in the same directory as require-jquery.js:

main.js:

    require(["jquery", "jquery.alpha", "jquery.beta"], function($) {
        //the jquery.alpha.js and jquery.beta.js plugins have been loaded.
        $(function() {
            $('body').alpha().beta();
        });
    });

In the require() call, "jquery" was referenced as a dependency. The require-jquery.js file has special code in it to register jQuery as a RequireJS module, and since it is registered as a module, you can get a handle on that module as the first argument to the function callback passed to require. In the above example, $ is used to reference the jQuery module.

Since jquery.alpha and jquery.beta are just plugins that augment jQuery, they do not return modules that you can reference as function arguments.

## Feel the need for speed § 3

Now your page is set up to be optimized very easily via the optimizer.

If you downloaded the jQuery sample project, then the optimizer that is part of the RequireJS source is already included.

If you are not using the jQuery sample project, get the optimizer by downloading the r.js file and place it anywhere you like outside your web development area.

For the purposes of this example, the RequireJS source is placed as a sibling to the webapp directory, which contains the HTML page and the scripts directory with all the scripts. Complete directory structure:

- r.js (the file that includes the optimizer)
- webapp/app.html
- webapp/scripts/main.js
- webapp/scripts/require-jquery.js
- webapp/scripts/jquery.alpha.js
- webapp/scripts/jquery.beta.js

Then, in the scripts directory that has require-jquery.js and main.js, create a file called app.build.js with the following contents:

    ({
        appDir: "../",
        baseUrl: "scripts",
        dir: "../../webapp-build",
        //Comment out the optimize line if you want
        //the code minified by UglifyJS.
        optimize: "none",

        paths: {
            "jquery": "require-jquery"
        },

        modules: [
            {
                name: "main",
                exclude: ["jquery"]
            }
        ]
    })

To use the optimizer, you need Node or Java 6 installed. These instructions assume Node is being used. See the Optimization page for more information.

To start the build, go to the webapp/scripts directory, execute the following command:

    node ../../r.js -o app.build.js

Now, in the webapp-build directory, main.js will have the main.js contents, jquery.alpha.js and jquery.beta.js inlined. If you then load the app.html file in the webapp-build directory, you should not see any network requests for jquery.alpha.js and jquery.beta.js.

## Advanced use § 4

The steps above make it easy start modular development with jQuery, particularly if you are using jQuery plugins that assume jQuery is already loaded in the page. The trade-off with the above approach is using a combined RequireJS and jQuery file.

Ideally you would not need to include jQuery with RequireJS, and just use RequireJS to load jQuery on demand. However, by default scripts can load out of order with RequireJS, and this does not work well with jQuery plugins.

Some options:

- Use the order plugin to load jQuery and the plugins you use in the correct order.
- Use the priority config to load jQuery before other scripts load. See the Alternate Integration section in the require-jquery project for more information.
- Wrap the plugins in a define() call.

Ideally all the jQuery plugins you use would optionally call define() to register as a module. Some of the plugins you use may already call define() to register as an AMD module. If they do not, then you can wrap the code yourself with this wrapper:

    define(['jquery'], function ($) {
        //Plugin code goes here.
    });

In addition, you can ask the plugin author to optionally calling define() in their code. The umdjs project has some resources and examples to help them.