~caneypuggies/reformedchurcheslocator/couchapp-backbone

« back to all changes in this revision

Viewing changes to _attachments/js/vendor/requirejs/docs/api.html

  • Committer: Tim Black
  • Date: 2013-09-16 22:50:16 UTC
  • Revision ID: tim@alwaysreformed.com-20130916225016-zk8jiba25z33ew7h
Versioned Bower vendor directory

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
<div id="directory" class="section">
 
2
<h1>RequireJS API</h1>
 
3
 
 
4
<span class="note">This is the <a href="https://github.com/jrburke/requirejs/wiki/Upgrading-to-RequireJS-2.0">RequireJS 2.0 API</a>. If you want 1.0: <a href="1.0/">Link to 1.0</a>.</span>
 
5
 
 
6
<ul class="index mono">
 
7
    <li class="hbox"><a href="#usage">Usage</a><span class="spacer boxFlex"></span><span class="sect">&sect;&sect; 1-1.2</span></li>
 
8
        <ul>
 
9
            <li class="hbox"><a href="#jsfiles">Load JavaScript Files</a><span class="spacer boxFlex"></span><span class="sect">&sect; 1.1</span></li>
 
10
            <li class="hbox"><a href="#define">Define a Module</a><span class="spacer boxFlex"></span><span class="sect">&sect; 1.2</span></li>
 
11
            <ul>
 
12
                <li class="hbox"><a href="#defsimple">Simple Name/Value Pairs</a><span class="spacer boxFlex"></span><span class="sect">&sect; 1.2.1</span></li>
 
13
                <li class="hbox"><a href="#deffunc">Definition Functions</a><span class="spacer boxFlex"></span><span class="sect">&sect; 1.2.2</span></li>
 
14
                <li class="hbox"><a href="#defdep">Definition Functions with Dependencies</a><span class="spacer boxFlex"></span><span class="sect">&sect; 1.2.3</span></li>
 
15
                <li class="hbox"><a href="#funcmodule">Define a Module as a Function</a><span class="spacer boxFlex"></span><span class="sect">&sect; 1.2.4</span></li>
 
16
                <li class="hbox"><a href="#cjsmodule">Define a Module with Simplified CommonJS Wrapper</a><span class="spacer boxFlex"></span><span class="sect">&sect; 1.2.5</span></li>
 
17
                <li class="hbox"><a href="#modulename">Define a Module with a name</a><span class="spacer boxFlex"></span><span class="sect">&sect; 1.2.6</span></li>
 
18
                <li class="hbox"><a href="#modulenotes">Other Module Notes</a><span class="spacer boxFlex"></span><span class="sect">&sect; 1.2.7</span></li>
 
19
                <li class="hbox"><a href="#circular">Circular Dependencies</a><span class="spacer boxFlex"></span><span class="sect">&sect; 1.2.8</span></li>
 
20
                <li class="hbox"><a href="#jsonp">Specify a JSONP Service Dependency</a><span class="spacer boxFlex"></span><span class="sect">&sect; 1.2.9</span></li>
 
21
                <li class="hbox"><a href="#undef">Undefining a Module</a><span class="spacer boxFlex"></span><span class="sect">&sect; 1.2.10</span></li>
 
22
 
 
23
            </ul>
 
24
        </ul>
 
25
    <li class="hbox"><a href="#mechanics">Mechanics</a><span class="spacer boxFlex"></span><span class="sect">&sect;&sect; 2</span></li>
 
26
    <li class="hbox"><a href="#config">Configuration Options</a><span class="spacer boxFlex"></span><span class="sect">&sect;&sect; 3</span></li>
 
27
    <li class="hbox"><a href="#advanced">Advanced Usage</a><span class="spacer boxFlex"></span><span class="sect">&sect;&sect; 4-4.6</span></li>
 
28
    <ul>
 
29
        <li class="hbox"><a href="#packages">Loading Modules from Packages</a><span class="spacer boxFlex"></span><span class="sect">&sect; 4.1</span></li>
 
30
        <li class="hbox"><a href="#multiversion">Multiversion Support</a><span class="spacer boxFlex"></span><span class="sect">&sect; 4.2</span></li>
 
31
        <li class="hbox"><a href="#afterload">Loading Code After Page Load</a><span class="spacer boxFlex"></span><span class="sect">&sect; 4.3</span></li>
 
32
        <li class="hbox"><a href="#webworker">Web Worker Support</a><span class="spacer boxFlex"></span><span class="sect">&sect; 4.4</span></li>
 
33
        <li class="hbox"><a href="#rhino">Rhino Support</a><span class="spacer boxFlex"></span><span class="sect">&sect; 4.5</span></li>
 
34
        <li class="hbox"><a href="#errors">Handling Errors</a><span class="spacer boxFlex"></span><span class="sect">&sect; 4.6</span></li>
 
35
    </ul>
 
36
    <li class="hbox"><a href="#plugins">Loader Plugins</a><span class="spacer boxFlex"></span><span class="sect">&sect;&sect; 5-5.4</span></li>
 
37
        <ul>
 
38
            <li class="hbox"><a href="#text">Specify a Text File Dependency</a><span class="spacer boxFlex"></span><span class="sect">&sect; 5.1</span></li>
 
39
            <li class="hbox"><a href="#pageload">Page Load Event Support/DOM Ready</a><span class="spacer boxFlex"></span><span class="sect">&sect; 5.2</span></li>
 
40
            <li class="hbox"><a href="#i18n">Define an I18N Bundle</a><span class="spacer boxFlex"></span><span class="sect">&sect; 5.3</span></li>
 
41
        </ul>
 
42
</ul>
 
43
</div>
 
44
 
 
45
<div class="section">
 
46
<h2>
 
47
<a href="#usage" name="usage">Usage</a>
 
48
<span class="sectionMark">&sect; 1</span>
 
49
</h2>
 
50
 
 
51
<h3>
 
52
<a href="#jsfiles" name="jsfiles">Load JavaScript Files</a>
 
53
<span class="sectionMark">&sect; 1.1</span>
 
54
</h3>
 
55
 
 
56
<p>RequireJS takes a different approach to script loading than traditional &lt;script&gt; tags. Its goal is to encourage modular code. While it can also run fast and optimize well, the primary goal is to encourage modular code. As part of that, it encourages using <strong>module IDs</strong> instead of URLs for script tags.</p>
 
57
 
 
58
<p>RequireJS loads all code relative to a <a href="#config-baseUrl">baseUrl</a>. The baseUrl is normally set to the same directory as the script used in a data-main attribute for the top level script to load for a page. The data-main attribute is a special attribute that require.js will check to start script loading. This example will end up with a baseUrl of <strong>scripts</strong>:</p>
 
59
 
 
60
<pre><code>&lt;!--This sets the baseUrl to the "scripts" directory, and
 
61
    loads a script that will have a module ID of 'main'--&gt;
 
62
&lt;script data-main="scripts/main.js" src="scripts/require.js"&gt;&lt;/script&gt;
 
63
</code></pre>
 
64
 
 
65
<p>Or, baseUrl can be set manually via the <a href="#config">RequireJS config</a>. If there is no explicit config and data-main is not used, then the default baseUrl is the directory that contains the HTML page running RequireJS.</p>
 
66
 
 
67
<p>RequireJS also assumes by default that all dependencies are scripts, so it does not expect to see a trailing ".js" suffix on module IDs. RequireJS will automatically add it when translating the module ID to a path. With the <a href="#config-paths">paths config</a>, you can set
 
68
up locations of a group of scripts. All of these capabilities allow you to use smaller strings for scripts as compared to traditional  &lt;script&gt; tags.</p>
 
69
 
 
70
<p>There may be times when you do want to reference a script directly and not conform to the "baseUrl + paths" rules for finding it. If a module ID has one of the following characterstics, the ID will not be passed through the "baseUrl + paths" configuration, and just be treated like a regular URL that is relative to the document:</p>
 
71
 
 
72
<ul>
 
73
<li>Ends in ".js".</li>
 
74
<li>Starts with a "/".</li>
 
75
<li>Contains an URL protocol, like "http:" or "https:".</li>
 
76
</ul>
 
77
 
 
78
<p>In general though, it is best to use the baseUrl and "paths" config to set paths for module IDs. By doing so, it gives you more flexibility in renaming and configuring the paths to different locations for optimization builds.</p>
 
79
 
 
80
<p>Similarly, to avoid a bunch of configuration, it is best to avoid deep folder hierarchies for scripts, and instead either keep all the scripts in baseUrl, or if you want to separate your library/vendor-supplied code from your app code, use a directory layout like this:</p>
 
81
 
 
82
<ul>
 
83
    <li>www/
 
84
    <ul>
 
85
        <li>index.html</li>
 
86
        <li>js/
 
87
        <ul>
 
88
            <li>app/
 
89
            <ul>
 
90
                <li>sub.js</li>
 
91
            </ul>
 
92
            </li>
 
93
            <li>lib/
 
94
            <ul>
 
95
                <li>jquery.js</li>
 
96
                <li>canvas.js</li>
 
97
            </ul></li>
 
98
            <li>app.js</li>
 
99
        </ul></li>
 
100
    </ul></li>
 
101
</ul>
 
102
 
 
103
<p>in index.html:</p>
 
104
 
 
105
<pre><code>&lt;script data-main="js/app.js" src="js/require.js"&gt;&lt;/script&gt;</code></pre>
 
106
 
 
107
<p>and in app.js:</p>
 
108
 
 
109
<pre><code>requirejs.config({
 
110
    //By default load any module IDs from js/lib
 
111
    baseUrl: 'js/lib',
 
112
    //except, if the module ID starts with "app",
 
113
    //load it from the js/app directory. paths
 
114
    //config is relative to the baseUrl, and
 
115
    //never includes a ".js" extension since
 
116
    //the paths config could be for a directory.
 
117
    paths: {
 
118
        app: '../app'
 
119
    }
 
120
});
 
121
 
 
122
// Start the main app logic.
 
123
requirejs(['jquery', 'canvas', 'app/sub'],
 
124
function   ($,        canvas,   sub) {
 
125
    //jQuery, canvas and the app/sub module are all
 
126
    //loaded and can be used here now.
 
127
});
 
128
</code></pre>
 
129
 
 
130
<p>Notice as part of that example, vendor libraries like jQuery did not have their version numbers in their file names. It is recommended to store that version info in a separate text file if you want to track it, or if you use a tool like <a href="https://github.com/volojs/volo">volo</a>, it will stamp the package.json with the version information but keep the file on disk as "jquery.js". This allows you to have the very minimal configuration instead of having to put an entry in the "paths" config for each library. For instance, configure "jquery" to be "jquery-1.7.2".</p>
 
131
 
 
132
<p>Ideally the scripts you load will be modules that are defined by calling <a href="#define">define()</a>. However, you may need to use some traditional/legacy "browser globals" scripts that do not express their dependencies via define(). For those, you can use the <a href="#config-shim">shim config</a>. To properly express their dependencies.</p>
 
133
 
 
134
<p>If you do not express the dependencies, you will likely get loading errors since RequireJS loads scripts asynchronously and out of order for speed.</p>
 
135
 
 
136
<h3>
 
137
<a href="#define" name="define">Define a Module</a>
 
138
<span class="sectionMark">&sect; 1.2</span>
 
139
</h3>
 
140
 
 
141
<p>A module is different from a traditional script file in that it defines a well-scoped object that avoids polluting the global namespace. It can explicitly list its dependencies and get a handle on those dependencies without needing to refer to global objects, but instead receive the dependencies as arguments to the function that defines the module. Modules in RequireJS are an extension of the <a href="http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth">Module Pattern</a>, with the benefit of not needing globals to refer to other modules.</p>
 
142
 
 
143
<p>The RequireJS syntax for modules allows them to be loaded as fast as possible, even out of order, but evaluated in the correct dependency order, and since global variables are not created, it makes it possible to <a href="#multiversion">load multiple versions of a module in a page</a>.</p>
 
144
 
 
145
<p>(If you are familiar with or are using CommonJS modules, then please also see <a href="commonjs.html">CommonJS Notes</a> for information on how the RequirejS module format maps to CommonJS modules).</p>
 
146
 
 
147
<p>There should only be <strong>one</strong> module definition per file on disk. The modules can be grouped into optimized bundles by the <a href="optimization.html">optimization tool</a>.</p>
 
148
 
 
149
<div class="subSection">
 
150
<h4>
 
151
<a href="#defsimple" name="defsimple">Simple Name/Value Pairs</a>
 
152
<span class="sectionMark">&sect; 1.2.1</span>
 
153
</h4>
 
154
 
 
155
<p>If the module does not have any dependencies, and it is just a collection of name/value pairs, then just pass an object literal to define():</p>
 
156
 
 
157
<pre><code>//Inside file my/shirt.js:
 
158
define({
 
159
    color: "black",
 
160
    size: "unisize"
 
161
});
 
162
</code></pre>
 
163
</div>
 
164
 
 
165
<div class="subSection">
 
166
<h4>
 
167
<a href="#deffunc" name="deffunc">Definition Functions</a>
 
168
<span class="sectionMark">&sect; 1.2.2</span>
 
169
</h4>
 
170
 
 
171
<p>If the module does not have dependencies, but needs to use a function to do some setup work, then define itself, pass a function to define():</p>
 
172
 
 
173
<pre><code>//my/shirt.js now does setup work
 
174
//before returning its module definition.
 
175
define(function () {
 
176
    //Do setup work here
 
177
 
 
178
    return {
 
179
        color: "black",
 
180
        size: "unisize"
 
181
    }
 
182
});
 
183
</code></pre>
 
184
</div>
 
185
 
 
186
<div href="#subSection" class="subSection">
 
187
<h4><a href="#defdep" name="defdep">Definition Functions with Dependencies</a><span class="sectionMark">&sect; 1.2.3</span></h4>
 
188
 
 
189
<p>If the module has dependencies, the first argument should be an array of dependency names, and the second argument should be a definition function. The function will be called to define the module once all dependencies have loaded. The function should return an object that defines the module. The dependencies will be passed to the definition function as function arguments, listed in the same order as the order in the dependency array:</p>
 
190
 
 
191
<pre><code>//my/shirt.js now has some dependencies, a cart and inventory
 
192
//module in the same directory as shirt.js
 
193
define(["./cart", "./inventory"], function(cart, inventory) {
 
194
        //return an object to define the "my/shirt" module.
 
195
        return {
 
196
            color: "blue",
 
197
            size: "large",
 
198
            addToCart: function() {
 
199
                inventory.decrement(this);
 
200
                cart.add(this);
 
201
            }
 
202
        }
 
203
    }
 
204
);
 
205
</code></pre>
 
206
 
 
207
<p>In this example, a my/shirt module is created. It depends on my/cart and my/inventory. On disk, the files are structured like this:</p>
 
208
 
 
209
<ul>
 
210
<li>my/cart.js</li>
 
211
<li>my/inventory.js</li>
 
212
<li>my/shirt.js</li>
 
213
</ul>
 
214
 
 
215
<p>The function call above specifies two arguments, "cart" and "inventory". These are the modules represented by the "./cart" and "./inventory" module names.</p>
 
216
 
 
217
<p>The function is not called until the my/cart and my/inventory modules have been loaded, and the function receives the modules as the "cart" and "inventory" arguments.</p>
 
218
 
 
219
<p>Modules that define globals are explicitly discouraged, so that multiple versions of a module can exist in a page at a time (see <strong>Advanced Usage</strong>). Also, the order of the function arguments should match the order of the dependencies.</p>
 
220
 
 
221
<p>The return object from the function call defines the "my/shirt" module. By defining modules in this way, "my/shirt" does not exist as a global object.</p>
 
222
</div>
 
223
 
 
224
<div class="subSection">
 
225
<h4><a href="#funcmodule" name="funcmodule">Define a Module as a Function</a><span class="sectionMark">&sect; 1.2.4</span></h4>
 
226
 
 
227
<p>Modules do not have to return objects. Any valid return value from a function is allowed. Here is a module that returns a function as its module definition:</p>
 
228
 
 
229
<pre><code>//A module definition inside foo/title.js. It uses
 
230
//my/cart and my/inventory modules from before,
 
231
//but since foo/bar.js is in a different directory than
 
232
//the "my" modules, it uses the "my" in the module dependency
 
233
//name to find them. The "my" part of the name can be mapped
 
234
//to any directory, but by default, it is assumed to be a
 
235
//sibling to the "foo" directory.
 
236
define(["my/cart", "my/inventory"],
 
237
    function(cart, inventory) {
 
238
        //return a function to define "foo/title".
 
239
        //It gets or sets the window title.
 
240
        return function(title) {
 
241
            return title ? (window.title = title) :
 
242
                   inventory.storeName + ' ' + cart.name;
 
243
        }
 
244
    }
 
245
);
 
246
</code></pre>
 
247
</div>
 
248
 
 
249
 
 
250
<div class="subSection">
 
251
<h4><a href="#cjsmodule" name="cjsmodule">Define a Module with Simplified CommonJS Wrapper</a><span class="sectionMark">&sect; 1.2.5</span></h4>
 
252
 
 
253
<p>If you wish to reuse some code that was written in the traditional <a href="http://wiki.commonjs.org/wiki/Modules/1.1.1">CommonJS module format</a> it may be difficult to re-work to the array of dependencies used above, and you may prefer to have
 
254
direct alignment of dependency name to the local variable used for that dependency. You can use the <a href="commonjs.html">simplified CommonJS wrapper</a> for those cases:</p>
 
255
 
 
256
 
 
257
<pre><code>define(function(require, exports, module) {
 
258
        var a = require('a'),
 
259
            b = require('b');
 
260
 
 
261
        //Return the module value
 
262
        return function () {};
 
263
    }
 
264
);
 
265
</code></pre>
 
266
 
 
267
<p>This wrapper relies on Function.prototype.toString() to give a useful string value of the function contents. This does not work on some devices like the PS3 and some older Opera mobile browsers. Use the <a href="optimization.html">optimizer</a> to pull out the dependencies in the array format for use on those devices.</p>
 
268
 
 
269
<p>More information is available on the <a href="commonjs.html">CommonJS page</a>, and in the in the <a href="whyamd.html#sugar">"Sugar" section in the Why AMD page</a>.
 
270
</div>
 
271
 
 
272
 
 
273
<div class="subSection">
 
274
<h4><a href="#modulename" name="modulename">Define a Module with a Name</a><span class="sectionMark">&sect; 1.2.6</span></h4>
 
275
 
 
276
<p>You may encounter some define() calls that include a name for the module as the first argument to define():</p>
 
277
 
 
278
<pre><code>    //Explicitly defines the "foo/title" module:
 
279
    define("foo/title",
 
280
        ["my/cart", "my/inventory"],
 
281
        function(cart, inventory) {
 
282
            //Define foo/title object in here.
 
283
       }
 
284
    );
 
285
</code></pre>
 
286
 
 
287
<p>These are normally generated by the <a href="optimization.html">optimization tool</a>. You can explicitly name modules yourself, but it makes the modules less portable -- if you move the file to another directory you will need to change the name. It is normally best to avoid coding in a name for the module and just let the optimization tool burn in the module names. The optimization tool needs to add the names so that more than one module can be bundled in a file, to allow for faster loading in the browser.</p>
 
288
</div>
 
289
 
 
290
<div class="subSection">
 
291
 
 
292
<h4><a href="#modulenotes" name="modulenotes">Other Module Notes</a><span class="sectionMark">&sect; 1.2.7</span></h4>
 
293
 
 
294
<p id="modulenotes-onemodule"><strong>One module per file.</strong>: Only one module should be defined per JavaScript file, given the nature of the module name-to-file-path lookup algorithm. Multiple modules will be grouped into optimized files by the <a href="optimization.html">optimization tool</a>, but you should only use the optimization tool to place more than one module in a file.</p>
 
295
 
 
296
<p id="modulenotes-relative"><strong>Relative module names inside define()</strong>: For require("./relative/name") calls that can happen inside a define() function call, be sure to ask for "require" as a dependency, so that the relative name is resolved correctly:</p>
 
297
 
 
298
<pre><code>define(["require", "./relative/name"], function(require) {
 
299
    var mod = require("./relative/name");
 
300
});
 
301
</code></pre>
 
302
 
 
303
<p>Or better yet, use the shortened syntax that is available for use with <a href="commonjs.html">translating CommonJS</a> modules:</p>
 
304
 
 
305
<pre><code>define(function(require) {
 
306
    var mod = require("./relative/name");
 
307
});
 
308
</code></pre>
 
309
 
 
310
<p>This form will use Function.prototype.toString() to find the require() calls, and add them to the dependency array, along with "require", so the code will work correctly with relative paths.</p>
 
311
 
 
312
<p>Relative paths are really useful if you are creating a few modules inside a directory, so that you can share the directory with other people or other projects, and you want to be able to get a handle on the sibling modules in that directory without
 
313
having to know the directory's name.</p>
 
314
 
 
315
<p id="modulenotes-urls"><strong>Generate URLs relative to module</strong>: You may need to generate an URL that is relative to a module. To do so, ask for "require" as a dependency and then use require.toUrl() to generate the URL:</p>
 
316
 
 
317
<pre><code>define(["require"], function(require) {
 
318
    var cssUrl = require.toUrl("./style.css");
 
319
});
 
320
</code></pre>
 
321
 
 
322
<p id="modulenotes-console"><strong>Console debugging</strong>: If you need to work with a module you already loaded via a require(["module/name"], function(){}) call in the JavaScript console, then you can use  the require() form that just uses the string name of the module to fetch it:</p>
 
323
 
 
324
<pre><code>require("module/name").callSomeFunction()
 
325
</code></pre>
 
326
 
 
327
<p>Note this only works if "module/name" was previously loaded via the async version of require: require(["module/name"]). If using a relative path, like './module/name', those only work inside define</p>
 
328
</div>
 
329
 
 
330
<div class="subSection">
 
331
<h4><a href="#circular" name="circular">Circular Dependencies</a><span class="sectionMark">&sect; 1.2.8</span></h4>
 
332
 
 
333
<p>If you define a circular dependency (a needs b and b needs a), then in this case when b's module function is called, it will get an undefined value for a. b can fetch a later after modules have been defined by using the require() method (be sure to specify require as a dependency so the right context is used to look up a):</p>
 
334
 
 
335
<pre><code>//Inside b.js:
 
336
define(["require", "a"],
 
337
    function(require, a) {
 
338
        //"a" in this case will be null if a also asked for b,
 
339
        //a circular dependency.
 
340
        return function(title) {
 
341
            return require("a").doSomething();
 
342
        }
 
343
    }
 
344
);
 
345
</code></pre>
 
346
 
 
347
<p>Normally you should not need to use require() to fetch a module, but instead rely on the module being passed in to the function as an argument. Circular dependencies are rare, and usually a sign that you might want to rethink the design. However, sometimes they are needed, and in that case, use require() as specified above.</p>
 
348
 
 
349
<p>If you are familiar with CommonJS modules, you could instead use <strong>exports</strong> to create an empty object for the module that is available immediately for reference by other modules. By doing this on both sides of a circular dependency, you can then safely hold on to the the other module. This only works if each module is exporting an object for the module value, not a function:</p>
 
350
 
 
351
<pre><code>//Inside b.js:
 
352
define(function(require, exports, module) {
 
353
    //If "a" has used exports, then we have a real
 
354
    //object reference here. However, we cannot use
 
355
    //any of a's properties until after b returns a value.
 
356
    var a = require("a");
 
357
 
 
358
    exports.foo = function () {
 
359
        return a.bar();
 
360
    };
 
361
});
 
362
</code></pre>
 
363
 
 
364
<p>Or, if you are using the dependency array approach, ask for the special
 
365
<a href="https://github.com/jrburke/requirejs/wiki/Differences-between-the-simplified-CommonJS-wrapper-and-standard-AMD-define#wiki-magic">'exports' dependency:</a></p>
 
366
 
 
367
<pre><code>//Inside b.js:
 
368
define(['a', 'exports'], function(a, exports) {
 
369
    //If "a" has used exports, then we have a real
 
370
    //object reference here. However, we cannot use
 
371
    //any of a's properties until after b returns a value.
 
372
 
 
373
    exports.foo = function () {
 
374
        return a.bar();
 
375
    };
 
376
});
 
377
</code></pre>
 
378
 
 
379
</div>
 
380
 
 
381
<div class="subSection">
 
382
<h4><a href="#jsonp" name="jsonp">Specify a JSONP Service Dependency</a><span class="sectionMark">&sect; 1.2.9</span></h4>
 
383
 
 
384
<p><a href="http://en.wikipedia.org/wiki/JSON#JSONP">JSONP</a> is a way of calling some services in JavaScript. It works across domains and it is an established approach to calling services that just require an HTTP GET via a script tag.</p>
 
385
 
 
386
<p>To use a JSONP service in RequireJS, specify "define" as the callback parameter's value. This means you can get the value of a JSONP URL as if it was a module definition.</p>
 
387
 
 
388
<p>Here is an example that calls a JSONP API endpoint. In this example, the JSONP callback parameter is called "callback", so "callback=define" tells the API to wrap the JSON response in a "define()" wrapper:</p>
 
389
 
 
390
<pre><code>require(["http://example.com/api/data.json?callback=define"],
 
391
    function (data) {
 
392
        //The data object will be the API response for the
 
393
        //JSONP data call.
 
394
        console.log(data);
 
395
    }
 
396
);
 
397
</code></pre>
 
398
 
 
399
<p>This use of JSONP should be limited to JSONP services for initial application setup. If the JSONP service times out, it means other modules you define via define() may not get executed, so the error handling is not robust.</p>
 
400
 
 
401
<p><strong>Only JSONP return values that are JSON objects are supported</strong>. A JSONP response that is an array, a string or a number will not work.</p>
 
402
 
 
403
<p>This functionality should not be used for long-polling JSONP connections -- APIs that deal with real time streaming. Those kinds of APIs should do more script cleanup after receiving each response, and RequireJS will only fetch a JSONP URL once -- subsequent uses of the same URL as a dependency in a require() or define() call will get a cached value.</p>
 
404
 
 
405
<p>Errors in loading a JSONP service are normally surfaced via timeouts for the service, since script tag loading does not give much detail into network problems. To detect errors, you can override requirejs.onError() to get errors. There is more information in the <a href="#errors">Handling Errors</a> section.</p>
 
406
 
 
407
</div>
 
408
 
 
409
 
 
410
<div class="subSection">
 
411
<h4><a href="#undef" name="undef">Undefining a Module</a><span class="sectionMark">&sect; 1.2.10</span></h4>
 
412
 
 
413
<p>There is a global function, <b>requirejs.undef()</b>, that allows undefining a module. It will reset the
 
414
loader's internal state to forget about the previous definition of the module.</p>
 
415
 
 
416
<p><b>However</b>, it will not remove the module from other modules that are already defined and got a
 
417
handle on that module as a dependency when they executed. So it is really only useful to use in
 
418
error situations when no other modules have gotten a handle on a module value, or as part of any future
 
419
module loading that may use that module. See the <a href="#errbacks">errback section</a> for an example.</p>
 
420
 
 
421
<p>If you want to do more sophisticated dependency graph analysis for undefining work, the semi-private
 
422
<a href="https://github.com/jrburke/requirejs/wiki/Internal-API:-onResourceLoad">onResourceLoad API</a> may be helpful.</p>
 
423
 
 
424
</div>
 
425
 
 
426
 
 
427
</div>
 
428
 
 
429
<div class="section">
 
430
<h2>
 
431
<a href="#mechanics" name="mechanics">Mechanics</a>
 
432
<span class="sectionMark">&sect; 2</span>
 
433
</h2>
 
434
 
 
435
<p>RequireJS loads each dependency as a script tag, using head.appendChild().</p>
 
436
 
 
437
<p>RequireJS waits for all dependencies to load, figures out the right order in which to call the functions that define the modules, then calls the module definition functions in the right order.</p>
 
438
 
 
439
<p>Using RequireJS in a server-side JavaScript environment that has synchronous loading should be as easy as redefining require.load(). The build system does this, the require.load method for that environment can be found in build/jslib/requirePatch.js.</p>
 
440
 
 
441
<p>In the future, this code may be pulled into the require/ directory as an optional module that you can load in your env to get the right load behavior based on the host environment.</p>
 
442
</div>
 
443
 
 
444
<div class="section">
 
445
<h2>
 
446
<a href="#config" name="config">Configuration Options</a>
 
447
<span class="sectionMark">&sect; 3</span>
 
448
</h2>
 
449
 
 
450
<p>When using require() in the top-level HTML page (or top-level script file that does not define a module), a configuration object can be passed as the first option:</p>
 
451
 
 
452
<pre><code>&lt;script src="scripts/require.js"&gt;&lt;/script&gt;
 
453
&lt;script&gt;
 
454
  require.config({
 
455
    baseUrl: "/another/path",
 
456
    paths: {
 
457
        "some": "some/v1.0"
 
458
    },
 
459
    waitSeconds: 15
 
460
  });
 
461
  require( ["some/module", "my/module", "a.js", "b.js"],
 
462
    function(someModule,    myModule) {
 
463
        //This function will be called when all the dependencies
 
464
        //listed above are loaded. Note that this function could
 
465
        //be called before the page is loaded.
 
466
        //This callback is optional.
 
467
    }
 
468
  );
 
469
&lt;/script&gt;
 
470
</code></pre>
 
471
 
 
472
<p>Also, you can define the config object as the global variable <code>require</code> <strong>before</strong> require.js is loaded, and have the values applied automatically.
 
473
This example specifies some dependencies to load as soon as require.js defines require():</p>
 
474
 
 
475
<pre><code>&lt;script&gt;
 
476
    var require = {
 
477
        deps: ["some/module1", "my/module2", "a.js", "b.js"],
 
478
        callback: function(module1, module2) {
 
479
            //This function will be called when all the dependencies
 
480
            //listed above in deps are loaded. Note that this
 
481
            //function could be called before the page is loaded.
 
482
            //This callback is optional.
 
483
        }
 
484
    };
 
485
&lt;/script&gt;
 
486
&lt;script src="scripts/require.js"&gt;&lt;/script&gt;
 
487
</code></pre>
 
488
 
 
489
<p><b>Note:</b> It is best to use <code>var require = {}</code> and do not use
 
490
<code>window.require = {}</code>, it will not behave correctly in IE.</p>
 
491
 
 
492
<p>Supported configuration options:</p>
 
493
 
 
494
<p id="config-baseUrl"><strong><a href="#config-baseUrl">baseUrl</a></strong>: the root path to use for all module lookups. So in the above example, "my/module"'s script tag will have a src="/another/path/my/module.js". baseUrl is <strong>not</strong> used when loading plain .js files (indicated by a dependency string <a href="#jsfiles">starting with a slash, has a protocol, or ends in .js</a>), those strings are used as-is, so a.js and b.js will be loaded from the same directory as the HTML page that contains the above snippet.</p>
 
495
 
 
496
<p>If no baseUrl is explicitly set in the configuration, the default value will be the location of the HTML page that loads require.js. If a <strong>data-main</strong> attribute is used, that path will become the baseUrl.</p>
 
497
 
 
498
<p>The baseUrl can be a URL on a different domain as the page that will load require.js. RequireJS script loading works across domains. The only restriction is on text content loaded by text! plugins: those paths should be on the same domain as the page, at least during development. The optimization tool will inline text! plugin resources so after using the optimization tool, you can use resources that reference text! plugin resources from another domain.</p>
 
499
 
 
500
<p id="config-paths"><strong><a href="#config-paths">paths</a></strong>: path mappings for module names not found directly under baseUrl. The path settings are assumed to be relative to baseUrl, unless the paths setting starts with a "/" or has a URL protocol in it ("like http:"). Using the above sample config, "some/module"'s script tag will be src="/another/path/some/v1.0/module.js".</p>
 
501
 
 
502
<p>The path that is used for a module name should <strong>not</strong> include an extension, since the path mapping could be for a directory. The path mapping code will automatically add the .js extension when mapping the module name to a path. If <a href="#modulenotes-urls">require.toUrl()</a> is used, it will add the appropriate extension, if it is for something like a text template.</p>
 
503
 
 
504
<p>When run in a browser, <a href="#pathsfallbacks">paths fallbacks</a> can be specified, to allow trying a load from a CDN location, but falling back to a local location if the CDN location fails to load.</p>
 
505
 
 
506
<p id="config-shim"><strong><a href="#config-shim">shim</a></strong>: Configure the dependencies, exports, and custom initialization for older, traditional "browser globals" scripts that do not use define() to declare the dependencies and set a module value.</p>
 
507
 
 
508
<p>Here is an example. It requires RequireJS 2.1.0+, and assumes backbone.js, underscore.js and jquery.js have been installed in the baseUrl directory. If not, then you may need to set a paths config for them:</p>
 
509
 
 
510
<pre><code>requirejs.config({
 
511
    //Remember: only use shim config for non-AMD scripts,
 
512
    //scripts that do not already call define(). The shim
 
513
    //config will not work correctly if used on AMD scripts,
 
514
    //in particular, the exports and init config will not
 
515
    //be triggered, and the deps config will be confusing
 
516
    //for those cases.
 
517
    shim: {
 
518
        'backbone': {
 
519
            //These script dependencies should be loaded before loading
 
520
            //backbone.js
 
521
            deps: ['underscore', 'jquery'],
 
522
            //Once loaded, use the global 'Backbone' as the
 
523
            //module value.
 
524
            exports: 'Backbone'
 
525
        },
 
526
        'underscore': {
 
527
            exports: '_'
 
528
        },
 
529
        'foo': {
 
530
            deps: ['bar'],
 
531
            exports: 'Foo',
 
532
            init: function (bar) {
 
533
                //Using a function allows you to call noConflict for
 
534
                //libraries that support it, and do other cleanup.
 
535
                //However, plugins for those libraries may still want
 
536
                //a global. "this" for the function will be the global
 
537
                //object. The dependencies will be passed in as
 
538
                //function arguments. If this function returns a value,
 
539
                //then that value is used as the module export value
 
540
                //instead of the object found via the 'exports' string.
 
541
                //Note: jQuery registers as an AMD module via define(),
 
542
                //so this will not work for jQuery. See notes section
 
543
                //below for an approach for jQuery.
 
544
                return this.Foo.noConflict();
 
545
            }
 
546
        }
 
547
    }
 
548
});
 
549
 
 
550
//Then, later in a separate file, call it 'MyModel.js', a module is
 
551
//defined, specifying 'backbone' as a dependency. RequireJS will use
 
552
//the shim config to properly load 'backbone' and give a local
 
553
//reference to this module. The global Backbone will still exist on
 
554
//the page too.
 
555
define(['backbone'], function (Backbone) {
 
556
  return Backbone.Model.extend({});
 
557
});
 
558
</code></pre>
 
559
 
 
560
<p>In RequireJS 2.0.*, the "exports" property in the shim config could have
 
561
    been a function instead of a string. In that case, it functioned
 
562
the same as the "init" property as shown above. The "init" pattern is used in
 
563
RequireJS 2.1.0+ so a string value for <code>exports</code> can be used for
 
564
<a href="#config-enforceDefine">enforceDefine</a>, but then allow
 
565
functional work once the library is known to have loaded.</p>
 
566
 
 
567
<p>For "modules" that are just jQuery or Backbone plugins that do not need to export
 
568
any module value, the shim config can just be an array of dependencies:</p>
 
569
 
 
570
<pre><code>requirejs.config({
 
571
    shim: {
 
572
        'jquery.colorize': ['jquery'],
 
573
        'jquery.scroll': ['jquery'],
 
574
        'backbone.layoutmanager': ['backbone']
 
575
    }
 
576
});
 
577
</code></pre>
 
578
 
 
579
<p>Note however if you want to get 404 load detection in IE so that you can  use paths fallbacks or errbacks, then a string exports value should be given so the loader can check if the scripts actually
 
580
loaded (a return from init is <strong>not</strong> used for <code>enforceDefine</code> checking):</p>
 
581
 
 
582
<pre><code>requirejs.config({
 
583
    shim: {
 
584
        'jquery.colorize': {
 
585
            deps: ['jquery'],
 
586
            exports: 'jQuery.fn.colorize'
 
587
        },
 
588
        'jquery.scroll': {
 
589
            deps: ['jquery'],
 
590
            exports: 'jQuery.fn.scroll'
 
591
        },
 
592
        'backbone.layoutmanager': {
 
593
            deps: ['backbone']
 
594
            exports: 'Backbone.LayoutManager'
 
595
        }
 
596
    }
 
597
});
 
598
</code></pre>
 
599
 
 
600
<p><b>Important notes for "shim" config:</b></p>
 
601
 
 
602
<ul>
 
603
    <li>The shim config only sets up code relationships. To load modules that
 
604
    are part of or use shim config, a normal require/define call is needed. Setting shim by
 
605
    itself does not trigger code to load.</li>
 
606
    <li>Only use other "shim" modules as dependencies for shimmed scripts, or
 
607
    AMD libraries that have no dependencies and call define() after they also
 
608
    create a global (like jQuery or lodash). Otherwise, if you use an AMD
 
609
    module as a dependency for a shim config module, after a build, that
 
610
    AMD module may not be evaluated until after the shimmed code in the build
 
611
    executes, and an error will occur. The ultimate fix is to upgrade all the
 
612
    shimmed code to have optional AMD define() calls.</li>
 
613
    <li>The init function will <strong>not</strong> be called for AMD modules.
 
614
    For example, you cannot use a shim init function to call jQuery's noConflict.
 
615
    See <a href="jquery.html#noconflictmap">Mapping Modules to use noConflict</a>
 
616
    for an alternate approach to jQuery.</li>
 
617
    <li>Shim config is not supported when running AMD modules in node via RequireJS (it works for optimizer use though). Depending on the module being shimmed, it may fail in Node because Node does not have the same global environment as browsers. As of RequireJS 2.1.7, it will warn you in the console that shim config is not supported, and it may or may not work. If you wish to suppress that message, you can pass <code>requirejs.config({ suppress: { nodeShim: true }});</code>.</li>
 
618
</ul>
 
619
 
 
620
<p><b>Important optimizer notes for "shim" config</b>:</p>
 
621
 
 
622
<ul>
 
623
    <li>You should use the <a href="optimization.html#mainConfigFile">mainConfigFile build option</a> to specify the file where to find the shim config. Otherwise the optimizer will not know of the shim config. The other option is to duplicate the shim config in the build profile.</li>
 
624
    <li>Do not mix CDN loading with shim config in a build. Example scenario: you load jQuery from the CDN but use the shim config to load something like the stock version of Backbone that depends on jQuery. When you do the build, be sure to inline jQuery in the built file and do not load it from the CDN. Otherwise, Backbone will be inlined in the built file and it will execute before the CDN-loaded jQuery will load. This is because the shim config just delays loading of the files until dependencies are loaded, but does not do any auto-wrapping of define. After a build, the dependencies are already inlined, the shim config cannot delay execution of the non-define()'d code until later. define()'d modules do work with CDN loaded code after a build because they properly wrap their source in define factory function that will not execute until dependencies are loaded. So the lesson: shim config is a stop-gap measure for non-modular code, legacy code. define()'d modules are better.</li>
 
625
    <li>For local, multi-file builds, the above CDN advice also applies. For any shimmed script, its dependencies <strong>must</strong> be loaded before the shimmed script executes. This means either building its dependencies directly in the buid layer that includes the shimmed script, or loading its dependencies with a <code>require([], function (){})</code> call, then doing a nested <code>require([])</code> call for the build layer that has the shimmed script.</li>
 
626
    <li>If you are using uglifyjs to minify the code, <strong>do not</strong> set the uglify
 
627
        option <code>toplevel</code> to true, or if using the command line
 
628
        <strong>do not</strong> pass <code>-mt</code>. That option mangles
 
629
        the global names that shim uses to find exports.</li>
 
630
</ul>
 
631
 
 
632
<p id="config-map"><strong><a href="#config-map">map</a></strong>: For the given module prefix, instead of loading the module with the given ID, substitute a different module ID.</p>
 
633
 
 
634
<p>This sort of capability is really important for larger projects which may have
 
635
two sets of modules that need to use two different versions of 'foo', but they
 
636
still need to cooperate with each other.</p>
 
637
 
 
638
<p>This is not possible with the <a href="#multiversion">context-backed multiversion support</a>. In addition, the <a href="#config-paths">paths config</a> is only for setting up root paths for module IDs, not for mapping one module ID to another one.</p>
 
639
 
 
640
<p>map example:</p>
 
641
 
 
642
<pre><code>requirejs.config({
 
643
    map: {
 
644
        'some/newmodule': {
 
645
            'foo': 'foo1.2'
 
646
        },
 
647
        'some/oldmodule': {
 
648
            'foo': 'foo1.0'
 
649
        }
 
650
    }
 
651
});
 
652
</code></pre>
 
653
 
 
654
<p>If the modules are laid out on disk like this:</p>
 
655
 
 
656
<ul>
 
657
    <li>foo1.0.js</li>
 
658
    <li>foo1.2.js</li>
 
659
    <li>some/
 
660
        <ul>
 
661
            <li>newmodule.js</li>
 
662
            <li>oldmodule.js</li>
 
663
        </ul>
 
664
    </li>
 
665
</ul>
 
666
 
 
667
<p>When 'some/newmodule' does `require('foo')` it will get the foo1.2.js file,
 
668
and when 'some/oldmodule' does `require('foo')` it will get the foo1.0.js file.</p>
 
669
 
 
670
<p>This feature only works well for scripts that are real AMD modules that call
 
671
define() and register as anonymous modules. Also, <strong>only use absolute module IDs</strong> for map config. Relative IDs (like <code>'../some/thing'</code>) do not work.</p>
 
672
 
 
673
<p>There is also support for a "*" map value which means "for all modules loaded, use this map config". If there is a more specific map config, that one will take precedence over the star config. Example:</p>
 
674
 
 
675
<pre><code>
 
676
requirejs.config({
 
677
    map: {
 
678
        '*': {
 
679
            'foo': 'foo1.2'
 
680
        },
 
681
        'some/oldmodule': {
 
682
            'foo': 'foo1.0'
 
683
        }
 
684
    }
 
685
});
 
686
</code></pre>
 
687
 
 
688
<p>Means that for any module except "some/oldmodule", when "foo" is wanted, use "foo1.2" instead. For "some/oldmodule" only, use "foo1.0" when it asks for "foo".</p>
 
689
 
 
690
<p id="config-moduleconfig"><strong><a href="#config-moduleconfig">config</a></strong>: There is a common need to pass configuration info to a module.  That configuration info is usually known as part of the application, and there needs to be a way to pass that down to a module. In RequireJS, that is done with the <b>config</b> option for requirejs.config(). Modules can then read that info by asking for the special dependency "module" and calling <b>module.config()</b>. Example:</p>
 
691
 
 
692
<pre><code>requirejs.config({
 
693
    config: {
 
694
        'bar': {
 
695
            size: 'large'
 
696
        },
 
697
        'baz': {
 
698
            color: 'blue'
 
699
        }
 
700
    }
 
701
});
 
702
 
 
703
//bar.js, which uses simplified CJS wrapping:
 
704
//http://requirejs.org/docs/whyamd.html#sugar
 
705
define(function (require, exports, module) {
 
706
    //Will be the value 'large'
 
707
    var size = module.config().size;
 
708
});
 
709
 
 
710
//baz.js which uses a dependency array,
 
711
//it asks for the special module ID, 'module':
 
712
//https://github.com/jrburke/requirejs/wiki/Differences-between-the-simplified-CommonJS-wrapper-and-standard-AMD-define#wiki-magic
 
713
define(['module'], function (module) {
 
714
    //Will be the value 'blue'
 
715
    var color = module.config().color;
 
716
});
 
717
</code></pre>
 
718
 
 
719
<p>For passing config to a <a href="#packages">package</a>, target the main module in the package,
 
720
    not the package ID:</p>
 
721
 
 
722
<pre><code>requirejs.config({
 
723
    //Pass an API key for use in the pixie package's
 
724
    //main module.
 
725
    config: {
 
726
        'pixie/index': {
 
727
            apiKey: 'XJKDLNS'
 
728
        }
 
729
    },
 
730
    //Set up config for the "pixie" package, whose main
 
731
    //module is the index.js file in the pixie folder.
 
732
    packages: [
 
733
        {
 
734
            name: 'pixie',
 
735
            main: 'index'
 
736
        }
 
737
    ]
 
738
});
 
739
</code></pre>
 
740
 
 
741
<p id="config-packages"><strong><a href="#config-packages">packages</a></strong>: configures loading modules from CommonJS packages. See the <a href="#packages">packages topic</a> for more information.</p>
 
742
 
 
743
<p id="config-waitSeconds"><strong><a href="#config-waitSeconds">waitSeconds</a></strong>: The number of seconds to wait before giving up on loading a script. Setting it to 0 disables the timeout. The default is 7 seconds.</p>
 
744
 
 
745
<p id="config-context"><strong><a href="#config-context">context</a></strong>: A name to give to a loading context. This allows require.js to load multiple versions of modules in a page, as long as each top-level require call specifies a unique context string. To use it correctly, see the <a href="#multiversion">Multiversion Support</a> section.</p>
 
746
 
 
747
<p id="config-deps"><strong><a href="#config-deps">deps</a></strong>: An array of dependencies to load. Useful when require is defined as a config object before require.js is loaded, and you want to specify dependencies to load as soon as require() is defined. Using deps is just like doing a <code>require([])</code> call, but done as soon as the loader has processed the configuration. <strong>It does not block</strong>
 
748
any other require() calls from starting their requests for modules, it is just a way to specify
 
749
some modules to load asynchronously as part of a config block.</p>
 
750
 
 
751
<p id="config-callback"><strong><a href="#config-callback">callback</a></strong>: A function to execute after <strong>deps</strong> have been loaded. Useful when require is defined as a config object before require.js is loaded, and you want to specify a function to require after the configuration's <strong>deps</strong> array has been loaded.</p>
 
752
 
 
753
<p id="config-enforceDefine"><strong><a href="#config-enforceDefine">enforceDefine</a></strong>: If set to true, an error will be thrown if a script loads that does not call define() or have a shim exports string value that can be checked. See <a href="#ieloadfail">Catching load failures in IE</a> for more information.</p>
 
754
 
 
755
<p id="config-xhtml"><strong><a href="#config-xhtml">xhtml</a></strong>: If set to true, document.createElementNS() will be used to create script elements.</p>
 
756
 
 
757
<p id="config-urlArgs"><strong><a href="#config-urlArgs">urlArgs</a></strong>: Extra query string arguments appended to URLs that RequireJS uses to fetch resources. Most useful to cache bust when the browser or server is not configured correctly. Example cache bust setting for urlArgs:</p>
 
758
 
 
759
<pre><code>urlArgs: "bust=" +  (new Date()).getTime()
 
760
</code></pre>
 
761
 
 
762
<p>During development it can be useful to use this, however <strong>be sure</strong> to remove it before deploying your code.</p>
 
763
 
 
764
<p id="config-scriptType"><strong><a href="#config-baseUrl">scriptType</a></strong>: Specify the value for the type="" attribute used for script tags inserted into the document by RequireJS. Default is "text/javascript". To use Firefox's JavaScript 1.8 features, use "text/javascript;version=1.8".</p>
 
765
 
 
766
</div>
 
767
 
 
768
<div class="section">
 
769
<h2>
 
770
<a href="#advanced" name="advanced">Advanced Usage</a>
 
771
<span class="sectionMark">&sect; 4</span>
 
772
</h2>
 
773
 
 
774
<h3><a href="#packages" name="packages">Loading Modules from Packages</a><span class="sectionMark">&sect; 4.1</span></h3>
 
775
 
 
776
<p>RequireJS supports loading modules that are in a <a href="http://wiki.commonjs.org/wiki/Packages/1.1">CommonJS Packages</a> directory structure, but some additional configuration needs to be specified for it to work. Specifically, there is support for the following CommonJS Packages features:</p>
 
777
 
 
778
<ul>
 
779
<li>A package can be associated with a module name/prefix.</li>
 
780
<li>The package config can specify the following properties for a specific package:
 
781
<ul>
 
782
<li><strong>name</strong>: The name of the package (used for the module name/prefix mapping)</li>
 
783
<li><strong>location</strong>: The location on disk. Locations are relative to the baseUrl configuration value, unless they contain a protocol or start with a front slash (/).</li>
 
784
<li><strong>main</strong>: The name of the module inside the package that should be used when someone does a require for "packageName". The default value is "main", so only specify it if it differs from the default. The value is relative to the package folder.</li>
 
785
</ul></li>
 
786
</ul>
 
787
 
 
788
<p><strong>IMPORTANT NOTES</strong></p>
 
789
 
 
790
<ul>
 
791
<li>While the packages can have the CommonJS directory layout, the modules themselves should be in a module format that RequireJS can understand. Exception to the rule: if you are using the r.js Node adapter, the modules can be in the traditional CommonJS module format. You can use the <a href="commonjs.html#autoconversion">CommonJS converter tool</a> if you need to convert traditional CommonJS modules into the async module format that RequireJS uses.</li>
 
792
<li>Only one version of a package can be used in a project context at a time. You can use RequireJS <a href="#multiversion">multiversion support</a> to load two different module contexts, but if you want to use Package A and B in one context and they depend on different versions of Package C, then that will be a problem. This may change in the future.</li>
 
793
</ul>
 
794
 
 
795
<p>If you use a similar project layout as specified in the <a href="start.html">Start Guide</a>, the start of your web project would look something like this (Node/Rhino-based projects are similar, just use the contents of the <strong>scripts</strong> directory as the top-level project directory):</p>
 
796
 
 
797
<ul>
 
798
<li>project-directory/
 
799
<ul>
 
800
<li>project.html</li>
 
801
<li>scripts/
 
802
<ul>
 
803
<li>require.js</li>
 
804
</ul></li>
 
805
</ul></li>
 
806
</ul>
 
807
 
 
808
<p>Here is how the example directory layout looks with two packages, <strong>cart</strong> and <strong>store</strong>:</p>
 
809
 
 
810
<ul>
 
811
<li>project-directory/
 
812
<ul>
 
813
<li>project.html</li>
 
814
<li>cart/
 
815
<ul>
 
816
<li>main.js</li>
 
817
</ul></li>
 
818
<li>store/
 
819
<ul>
 
820
<li>main.js</li>
 
821
<li>util.js</li>
 
822
</ul></li>
 
823
<li>main.js</li>
 
824
<li>require.js</li>
 
825
</ul></li>
 
826
</ul></li>
 
827
</ul>
 
828
 
 
829
<p><strong>project.html</strong> will have a script tag like this:</p>
 
830
 
 
831
<pre><code>&lt;script data-main="scripts/main" src="scripts/require.js"&gt;&lt;/script&gt;
 
832
</code></pre>
 
833
 
 
834
<p>This will instruct require.js to load scripts/main.js. <strong>main.js</strong> uses the "packages" config to set up packages that are relative to require.js, which in this case are the source packages "cart" and "store":</p>
 
835
 
 
836
<pre><code>//main.js contents
 
837
//Pass a config object to require
 
838
require.config({
 
839
    "packages": ["cart", "store"]
 
840
});
 
841
 
 
842
require(["cart", "store", "store/util"],
 
843
function (cart,   store,   util) {
 
844
    //use the modules as usual.
 
845
});
 
846
</code></pre>
 
847
 
 
848
<p>A require of "cart" means that it will be loaded from <strong>scripts/cart/main.js</strong>, since "main" is the default main module setting supported by RequireJS. A require of "store/util" will be loaded from <strong>scripts/store/util.js</strong>.</p>
 
849
 
 
850
<p>If the "store" package did not follow the "main.js" convention, and looked more like this:</p>
 
851
 
 
852
<ul>
 
853
<li>project-directory/
 
854
<ul>
 
855
<li>project.html</li>
 
856
<li>scripts/
 
857
<ul>
 
858
<li>cart/
 
859
<ul>
 
860
<li>main.js</li>
 
861
</ul></li>
 
862
<li>store/
 
863
<ul>
 
864
<li>store.js</li>
 
865
<li>util.js</li>
 
866
</ul></li>
 
867
<li>main.js</li>
 
868
<li>package.json</li>
 
869
<li>require.js</li>
 
870
</ul></li>
 
871
</ul></li>
 
872
</ul>
 
873
 
 
874
<p>Then the RequireJS configuration would look like so:</p>
 
875
 
 
876
<pre><code>require.config({
 
877
    packages: [
 
878
        "cart",
 
879
        {
 
880
            name: "store",
 
881
            main: "store"
 
882
        }
 
883
    ]
 
884
});
 
885
</code></pre>
 
886
 
 
887
<p>To avoid verbosity, it is strongly suggested to always use packages that use "main" convention in their structure.</p>
 
888
 
 
889
<h3><a href="#multiversion" name="multiversion">Multiversion Support</a><span class="sectionMark">&sect; 4.2</span></h3>
 
890
 
 
891
<p>As mentioned in <a href="#config">Configuration Options</a>, multiple versions of a module can be loaded in a page by using different "context" configuration options. require.config() returns a require function that will use the context configuration. Here is an example that loads two different versions of the alpha and beta modules (this example is taken from one of the test files):</p>
 
892
 
 
893
<pre><code>&lt;script src="../require.js"&gt;&lt;/script&gt;
 
894
&lt;script&gt;
 
895
var reqOne = require.config({
 
896
  context: "version1",
 
897
  baseUrl: "version1"
 
898
});
 
899
 
 
900
reqOne(["require", "alpha", "beta",],
 
901
function(require,   alpha,   beta) {
 
902
  log("alpha version is: " + alpha.version); //prints 1
 
903
  log("beta version is: " + beta.version); //prints 1
 
904
 
 
905
  setTimeout(function() {
 
906
    require(["omega"],
 
907
      function(omega) {
 
908
        log("version1 omega loaded with version: " +
 
909
             omega.version); //prints 1
 
910
      }
 
911
    );
 
912
  }, 100);
 
913
});
 
914
 
 
915
var reqTwo = require.config({
 
916
      context: "version2",
 
917
      baseUrl: "version2"
 
918
    });
 
919
 
 
920
reqTwo(["require", "alpha", "beta"],
 
921
function(require,   alpha,   beta) {
 
922
  log("alpha version is: " + alpha.version); //prints 2
 
923
  log("beta version is: " + beta.version); //prints 2
 
924
 
 
925
  setTimeout(function() {
 
926
    require(["omega"],
 
927
      function(omega) {
 
928
        log("version2 omega loaded with version: " +
 
929
            omega.version); //prints 2
 
930
      }
 
931
    );
 
932
  }, 100);
 
933
});
 
934
&lt;/script&gt;
 
935
</code></pre>
 
936
 
 
937
<p>Note that "require" is specified as a dependency for the module. This allows the require() function that is passed to the function callback to use the right context to load the modules correctly for multiversion support. If "require" is not specified as a dependency, then there will likely be an error.</p>
 
938
 
 
939
<h3><a href="#afterload" name="afterload">Loading Code After Page Load</a><span class="sectionMark">&sect; 4.3</span></h3>
 
940
 
 
941
<p>The example above in the <strong>Multiversion Support</strong> section shows how code can later be loaded by nested require() calls. </p>
 
942
 
 
943
<h3><a href="#webworker" name="webworker">Web Worker Support</a><span class="sectionMark">&sect; 4.4</span></h3>
 
944
 
 
945
<p>As of release 0.12, RequireJS can be run inside a Web Worker. Just use importScripts() inside a web worker to load require.js (or the JS file that contains the require() definition), then call require.</p>
 
946
 
 
947
<p>You will likely need to set the <strong>baseUrl</strong> <a href="#config">configuration option</a> to make sure require() can find the scripts to load.</p>
 
948
 
 
949
<p>You can see an example of its use by looking at one of the files used in <a href="http://github.com/jrburke/requirejs/blob/master/tests/workers.js">the unit test</a>.</p>
 
950
 
 
951
<h3><a href="#rhino" name="rhino">Rhino Support</a><span class="sectionMark">&sect; 4.5</span></h3>
 
952
 
 
953
<p>RequireJS can be used in Rhino via the <a href="download.html#rjs">r.js adapter</a>.
 
954
See <a href="https://github.com/jrburke/r.js/blob/master/README.md">the r.js README</a> for more information.</p>
 
955
 
 
956
<h3><a href="#errors" name="errors">Handling Errors</a><span class="sectionMark">&sect; 4.6</span></h3>
 
957
 
 
958
<p>The general class of errors are 404s for scripts (not found), network timeouts or errors in the scripts that are loaded. RequireJS has a few tools to deal with them: require-specific errbacks, a "paths" array config, and a global requirejs.onError.</p>
 
959
 
 
960
<p>The error object passed to errbacks and the global requirejs.onError function will usually contain two custom properties:</p>
 
961
 
 
962
<ul>
 
963
<li><strong>requireType</strong>: A string value with a general classification, like "timeout", "nodefine", "scripterror".</li>
 
964
<li><strong>requireModules</strong>: an array of module names/URLs that timed out.</li>
 
965
</ul>
 
966
 
 
967
<p>If you get an error with a requireModules, it probably means other modules that depend on the modules in that requireModules array are not defined.</p>
 
968
 
 
969
<h4>
 
970
<a href="#ieloadfail" name="ieloadfail">Catching load failures in IE</a>
 
971
<span class="sectionMark">&sect; 4.6.1</span>
 
972
</h4>
 
973
 
 
974
<p>Internet Explorer has a set of problems that make it difficult to detect load failures for errbacks/paths fallbacks:</p>
 
975
 
 
976
<ul>
 
977
    <li>script.onerror does not work in IE 6-8. There is no way to know if loading a script generates a 404, worse, it triggers the onreadystatechange with a complete state even in a 404 case.</li>
 
978
    <li>script.onerror does work in IE 9+, but it has a bug where it does not fire script.onload event handlers right after execution of script, so it cannot support the standard method of allowing anonymous AMD modules. So script.onreadystatechange is still used. However, onreadystatechange fires with a complete state before the script.onerror function fires.</li>
 
979
</ul>
 
980
 
 
981
<p>So it is very difficult with IE to allow both anonymous AMD modules, which are a core benefit of AMD modules, and reliable detect errors.</p>
 
982
 
 
983
<p>However, if you are in a project that you know uses define() to declare all of its modules, or it uses the <a href="#config-shim">shim</a> config to specify string exports for anything that does not use define(), then if you set the <a href="#config-enforceDefine">enforceDefine</a> config value to true, the loader can confirm if a script load by checking for the define() call or the existence of the shim's exports global value.</p>
 
984
 
 
985
<p>So if you want to support Internet Explorer, catch load errors, and have modular code either through direct define() calls or shim config, always set <b>enforceDefine</b> to be true. See the next section for an example.</p>
 
986
 
 
987
<p><b>NOTE</b>: If you do set enforceDefine: true, and you use data-main="" to load your main JS module, then that main JS module <b>must call define()</b> instead of require() to load the code it needs. The main JS module can still call require/requirejs to set config values, but for loading modules it should use define().</p>
 
988
 
 
989
<p>If you then also use <a href="https://github.com/jrburke/almond">almond</a> to build your code without require.js, be sure to use the <a href="https://github.com/jrburke/r.js/blob/master/build/example.build.js#L289">insertRequire</a> build setting to insert a require call for the main module -- that serves the same purpose of the initial require() call that data-main does.</p>
 
990
 
 
991
<h4>
 
992
<a href="#errbacks" name="errbacks">require([]) errbacks</a>
 
993
<span class="sectionMark">&sect; 4.6.2</span>
 
994
</h4>
 
995
 
 
996
<p>Errbacks, when used with <a href="#undef">requirejs.undef()</a>, will allow you to detect if a module fails to load, undefine
 
997
that module, reset the config to a another location, then try again.</p>
 
998
 
 
999
<p>A common use case for this is to use a CDN-hosted version of a library, but if
 
1000
that fails, switch to loading the file locally:</p>
 
1001
 
 
1002
<pre><code>requirejs.config({
 
1003
    enforceDefine: true,
 
1004
    paths: {
 
1005
        jquery: 'http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min'
 
1006
    }
 
1007
});
 
1008
 
 
1009
//Later
 
1010
require(['jquery'], function ($) {
 
1011
    //Do something with $ here
 
1012
}, function (err) {
 
1013
    //The errback, error callback
 
1014
    //The error has a list of modules that failed
 
1015
    var failedId = err.requireModules && err.requireModules[0];
 
1016
    if (failedId === 'jquery') {
 
1017
        //undef is function only on the global requirejs object.
 
1018
        //Use it to clear internal knowledge of jQuery. Any modules
 
1019
        //that were dependent on jQuery and in the middle of loading
 
1020
        //will not be loaded yet, they will wait until a valid jQuery
 
1021
        //does load.
 
1022
        requirejs.undef(failedId);
 
1023
 
 
1024
        //Set the path to jQuery to local path
 
1025
        requirejs.config({
 
1026
            paths: {
 
1027
                jquery: 'local/jquery'
 
1028
            }
 
1029
        });
 
1030
 
 
1031
        //Try again. Note that the above require callback
 
1032
        //with the "Do something with $ here" comment will
 
1033
        //be called if this new attempt to load jQuery succeeds.
 
1034
        require(['jquery'], function () {});
 
1035
    } else {
 
1036
        //Some other error. Maybe show message to the user.
 
1037
    }
 
1038
});
 
1039
</code></pre>
 
1040
 
 
1041
<p>With `requirejs.undef()`, if you later set up a different config and try to
 
1042
load the same module, the loader will still remember which modules needed
 
1043
that dependency and finish loading them when the newly configured module loads.</p>
 
1044
 
 
1045
<p><b>Note</b>: errbacks only work with callback-style require calls, not define()
 
1046
calls. define() is only for declaring modules.</p>
 
1047
 
 
1048
<h4>
 
1049
<a href="#pathsfallbacks" name="pathsfallbacks">paths config fallbacks</a>
 
1050
<span class="sectionMark">&sect; 4.6.3</span>
 
1051
</h4>
 
1052
 
 
1053
<p>The above pattern for detecting a load failure, undef()ing a module, modifying paths and reloading is a common enough request that there is also a shorthand for it. The paths config allows array values:</p>
 
1054
 
 
1055
<pre><code>requirejs.config({
 
1056
    //To get timely, correct error triggers in IE, force a define/shim exports check.
 
1057
    enforceDefine: true,
 
1058
    paths: {
 
1059
        jquery: [
 
1060
            'http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min',
 
1061
            //If the CDN location fails, load from this location
 
1062
            'lib/jquery'
 
1063
        ]
 
1064
    }
 
1065
});
 
1066
 
 
1067
//Later
 
1068
require(['jquery'], function ($) {
 
1069
});
 
1070
</code></pre>
 
1071
 
 
1072
<p>This above code will try the CDN location, but if that fails, fall back to the local lib/jquery.js location.</p>
 
1073
 
 
1074
<p><b>Note</b>: paths fallbacks only work for exact module ID matches. This is
 
1075
different from normal paths config which can apply to any part of a module ID
 
1076
prefix segment. Fallbacks are targeted more for unusual error recovery, not
 
1077
a generic path search path solution, since those are inefficient in the browser.</p>
 
1078
 
 
1079
<h4>
 
1080
<a href="#requirejsonerror" name="requirejsonerror">Global requirejs.onError function</a>
 
1081
<span class="sectionMark">&sect; 4.6.4</span>
 
1082
</h4>
 
1083
 
 
1084
<p>To detect errors that are not caught by local errbacks, you can override requirejs.onError():</p>
 
1085
 
 
1086
<pre><code>requirejs.onError = function (err) {
 
1087
    console.log(err.requireType);
 
1088
    if (err.requireType === 'timeout') {
 
1089
        console.log('modules: ' + err.requireModules);
 
1090
    }
 
1091
 
 
1092
    throw err;
 
1093
};
 
1094
</code></pre>
 
1095
 
 
1096
</div>
 
1097
 
 
1098
<div class="section">
 
1099
<h2>
 
1100
<a href="#plugins" name="plugins">Loader Plugins</a>
 
1101
<span class="sectionMark">&sect; 5</span>
 
1102
</h2>
 
1103
 
 
1104
<p>RequireJS supports <a href="plugins.html">loader plugins</a>. This is a way to support dependencies that are not plain JS files, but are still important for a script to have loaded before it can do its work. The RequireJS wiki has <a href="https://github.com/jrburke/requirejs/wiki/Plugins">a list of plugins</a>. This section talks about some specific plugins that are maintained alongside RequireJS:</p>
 
1105
 
 
1106
<h3><a href="#text" name="text">Specify a Text File Dependency</a><span class="sectionMark">&sect; 5.1</span></h3>
 
1107
 
 
1108
<p>It is nice to build HTML using regular HTML tags, instead of building up DOM structures in script. However, there is no good way to embed HTML in a JavaScript file. The best that can be done is using a string of HTML, but that can be hard to manage, particularly for multi-line HTML.</p>
 
1109
 
 
1110
<p>RequireJS has a plugin, text.js, that can help with this issue. It will automatically be loaded if the text! prefix is used for a dependency. See the
 
1111
<a href="https://github.com/requirejs/text">text.js README</a> for more information.</p>
 
1112
 
 
1113
<h3><a href="#pageload" name="pageload">Page Load Event Support/DOM Ready</a><span class="sectionMark">&sect; 5.2</span></h3>
 
1114
 
 
1115
<p>It is possible when using RequireJS to load scripts quickly enough that they complete before the DOM is ready. Any work that tries to interact with the DOM should wait for the DOM to be ready. For modern browsers, this is done by waiting for the DOMContentLoaded event.</p>
 
1116
 
 
1117
<p>However, not all browsers in use support DOMContentLoaded. The domReady module implements a cross-browser method to determine when the DOM is ready. <a href="download.html#domReady">Download the module</a> and use it in your project like so:</p>
 
1118
 
 
1119
<pre><code>require(['domReady'], function (domReady) {
 
1120
  domReady(function () {
 
1121
    //This function is called once the DOM is ready.
 
1122
    //It will be safe to query the DOM and manipulate
 
1123
    //DOM nodes in this function.
 
1124
  });
 
1125
});
 
1126
</code></pre>
 
1127
 
 
1128
<p>Since DOM ready is a common application need, ideally the nested functions
 
1129
in the API above could be avoided. The domReady module also implements the <a href="plugins.html">Loader Plugin API</a>,
 
1130
so you can use the loader plugin syntax (notice the <b>!</b> in the domReady dependency) to force the
 
1131
require() callback function to wait for the DOM to be ready before executing. domReady will return
 
1132
the current document when used as a loader plugin:</p>
 
1133
 
 
1134
<pre><code>require(['domReady!'], function (doc) {
 
1135
    //This function is called once the DOM is ready,
 
1136
    //notice the value for 'domReady!' is the current
 
1137
    //document.
 
1138
});
 
1139
</code></pre>
 
1140
 
 
1141
<p><b>Note:</b> If the document takes a while to load (maybe it is a very large document, or has HTML script tags loading large JS files that block DOM completion until they are done), using domReady as a loader plugin may result in a RequireJS "timeout" error. If this a problem either increase the <a href="#config-waitSeconds">waitSeconds</a> configuration, or just use domReady as a module and
 
1142
call domReady() inside the require() callback.</p>
 
1143
 
 
1144
<h3><a href="#i18n" name="i18n">Define an I18N Bundle</a><span class="sectionMark">&sect; 5.3</span></h3>
 
1145
 
 
1146
<p>Once your web app gets to a certain size and popularity, localizing the strings in the interface and providing other locale-specific information becomes more useful. However, it can be cumbersome to work out a scheme that scales well for supporting multiple locales.</p>
 
1147
 
 
1148
<p>RequireJS allows you to set up a basic module that has localized information without forcing you to provide all locale-specific information up front. It can be added over time, and only strings/values that change between locales can be defined in the locale-specific file.</p>
 
1149
 
 
1150
<p>i18n bundle support is provided by the i18n.js plugin. It is automatically loaded when a module or dependency specifies the i18n! prefix (more info below). <a href="download.html#i18n">Download the plugin</a> and put it in the same directory as your app's main JS file.</p>
 
1151
 
 
1152
<p>To define a bundle, put it in a directory called "nls" -- the i18n! plugin assumes a module name with "nls" in it indicates an i18n bundle. The "nls" marker in the name tells the i18n plugin where to expect the locale directories (they should be immediate children of the nls directory). If you wanted to provide a bundle of color names in your "my" set of modules, create the directory structure like so:</p>
 
1153
 
 
1154
<ul>
 
1155
<li>my/nls/colors.js</li>
 
1156
</ul>
 
1157
 
 
1158
<p>The contents of that file should look like so:</p>
 
1159
 
 
1160
<pre><code>//my/nls/colors.js contents:
 
1161
define({
 
1162
    "root": {
 
1163
        "red": "red",
 
1164
        "blue": "blue",
 
1165
        "green": "green"
 
1166
    }
 
1167
});
 
1168
</code></pre>
 
1169
 
 
1170
<p>An object literal with a property of "root" defines this module. That is all you have to do to set the stage for later localization work.</p>
 
1171
 
 
1172
<p>You can then use the above module in another module, say, in a my/lamps.js file:</p>
 
1173
 
 
1174
<pre><code>//Contents of my/lamps.js
 
1175
define(["i18n!my/nls/colors"], function(colors) {
 
1176
    return {
 
1177
        testMessage: "The name for red in this locale is: " + colors.red
 
1178
    }
 
1179
});
 
1180
</code></pre>
 
1181
 
 
1182
<p>The my/lamps module has one property called "testMessage" that uses colors.red to show the localized value for the color red.</p>
 
1183
 
 
1184
<p>Later, when you want to add a specific translation to a file, say for the fr-fr locale, change my/nls/colors to look like so:</p>
 
1185
 
 
1186
<pre><code>//Contents of my/nls/colors.js
 
1187
define({
 
1188
    "root": {
 
1189
        "red": "red",
 
1190
        "blue": "blue",
 
1191
        "green": "green"
 
1192
    },
 
1193
    "fr-fr": true
 
1194
});
 
1195
</code></pre>
 
1196
 
 
1197
<p>Then define a file at my/nls/fr-fr/colors.js that has the following contents:</p>
 
1198
 
 
1199
<pre><code>//Contents of my/nls/fr-fr/colors.js
 
1200
define({
 
1201
    "red": "rouge",
 
1202
    "blue": "bleu",
 
1203
    "green": "vert"
 
1204
});
 
1205
</code></pre>
 
1206
 
 
1207
<p>RequireJS will use the browser's navigator.language or navigator.userLanguage property to determine what locale values to use for my/nls/colors, so your app does not have to change. If you prefer to set the locale, you can use the <a href="#moduleconfig">module config</a> to pass the locale to the plugin:</p>
 
1208
 
 
1209
<pre><code>requirejs.config({
 
1210
    config: {
 
1211
        //Set the config for the i18n
 
1212
        //module ID
 
1213
        i18n: {
 
1214
            locale: 'fr-fr'
 
1215
        }
 
1216
    }
 
1217
});
 
1218
</code></pre>
 
1219
 
 
1220
<p><strong>Note</strong> that RequireJS will always use a lowercase version of the locale, to avoid case issues, so all of the directories and files on disk for i18n bundles should use lowercase locales.</p>
 
1221
 
 
1222
<p>RequireJS is also smart enough to pick the right locale bundle, the one that most closely matches the ones provided by my/nls/colors. For instance, if the locale is "en-us", then the "root" bundle will be used. If the locale is "fr-fr-paris" then the "fr-fr" bundle will be used.</p>
 
1223
 
 
1224
<p>RequireJS also combines bundles together, so for instance, if the french bundle was defined like so (omitting a value for red):</p>
 
1225
 
 
1226
<pre><code>//Contents of my/nls/fr-fr/colors.js
 
1227
define({
 
1228
    "blue": "bleu",
 
1229
    "green": "vert"
 
1230
});
 
1231
</code></pre>
 
1232
 
 
1233
<p>Then the value for red in "root" will be used. This works for all locale pieces. If all the bundles listed below were defined, then RequireJS will use the values in the following priority order (the one at the top takes the most precedence):</p>
 
1234
 
 
1235
<ul>
 
1236
<li>my/nls/fr-fr-paris/colors.js</li>
 
1237
<li>my/nls/fr-fr/colors.js</li>
 
1238
<li>my/nls/fr/colors.js</li>
 
1239
<li>my/nls/colors.js</li>
 
1240
</ul>
 
1241
 
 
1242
<p>If you prefer to not include the root bundle in the top level module, you can define it like a normal locale bundle. In that case, the top level module would look like:</p>
 
1243
 
 
1244
<pre><code>//my/nls/colors.js contents:
 
1245
define({
 
1246
    "root": true,
 
1247
    "fr-fr": true,
 
1248
    "fr-fr-paris": true
 
1249
});
 
1250
</code></pre>
 
1251
 
 
1252
<p>and the root bundle would look like:</p>
 
1253
 
 
1254
<pre><code>//Contents of my/nls/root/colors.js
 
1255
define({
 
1256
    "red": "red",
 
1257
    "blue": "blue",
 
1258
    "green": "green"
 
1259
});
 
1260
</code></pre>
 
1261
 
 
1262
</div>