-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
api.html
1412 lines (1097 loc) · 76 KB
/
api.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<div id="directory" class="section">
<h1>RequireJS API</h1>
<ul class="index mono">
<li class="hbox"><a href="#usage">Usage</a><span class="spacer boxFlex"></span><span class="sect">§§ 1-1.3</span></li>
<ul>
<li class="hbox"><a href="#jsfiles">Load JavaScript Files</a><span class="spacer boxFlex"></span><span class="sect">§ 1.1</span></li>
<li class="hbox"><a href="#data-main">data-main Entry Point</a><span class="spacer boxFlex"></span><span class="sect">§ 1.2</span></li>
<li class="hbox"><a href="#define">Define a Module</a><span class="spacer boxFlex"></span><span class="sect">§ 1.3</span></li>
<ul>
<li class="hbox"><a href="#defsimple">Simple Name/Value Pairs</a><span class="spacer boxFlex"></span><span class="sect">§ 1.3.1</span></li>
<li class="hbox"><a href="#deffunc">Definition Functions</a><span class="spacer boxFlex"></span><span class="sect">§ 1.3.2</span></li>
<li class="hbox"><a href="#defdep">Definition Functions with Dependencies</a><span class="spacer boxFlex"></span><span class="sect">§ 1.3.3</span></li>
<li class="hbox"><a href="#funcmodule">Define a Module as a Function</a><span class="spacer boxFlex"></span><span class="sect">§ 1.3.4</span></li>
<li class="hbox"><a href="#cjsmodule">Define a Module with Simplified CommonJS Wrapper</a><span class="spacer boxFlex"></span><span class="sect">§ 1.3.5</span></li>
<li class="hbox"><a href="#modulename">Define a Module with a name</a><span class="spacer boxFlex"></span><span class="sect">§ 1.3.6</span></li>
<li class="hbox"><a href="#modulenotes">Other Module Notes</a><span class="spacer boxFlex"></span><span class="sect">§ 1.3.7</span></li>
<li class="hbox"><a href="#circular">Circular Dependencies</a><span class="spacer boxFlex"></span><span class="sect">§ 1.3.8</span></li>
<li class="hbox"><a href="#jsonp">Specify a JSONP Service Dependency</a><span class="spacer boxFlex"></span><span class="sect">§ 1.3.9</span></li>
<li class="hbox"><a href="#undef">Undefining a Module</a><span class="spacer boxFlex"></span><span class="sect">§ 1.3.10</span></li>
</ul>
</ul>
<li class="hbox"><a href="#mechanics">Mechanics</a><span class="spacer boxFlex"></span><span class="sect">§§ 2</span></li>
<li class="hbox"><a href="#config">Configuration Options</a><span class="spacer boxFlex"></span><span class="sect">§§ 3</span></li>
<li class="hbox"><a href="#advanced">Advanced Usage</a><span class="spacer boxFlex"></span><span class="sect">§§ 4-4.6</span></li>
<ul>
<li class="hbox"><a href="#packages">Loading Modules from Packages</a><span class="spacer boxFlex"></span><span class="sect">§ 4.1</span></li>
<li class="hbox"><a href="#multiversion">Multiversion Support</a><span class="spacer boxFlex"></span><span class="sect">§ 4.2</span></li>
<li class="hbox"><a href="#afterload">Loading Code After Page Load</a><span class="spacer boxFlex"></span><span class="sect">§ 4.3</span></li>
<li class="hbox"><a href="#webworker">Web Worker Support</a><span class="spacer boxFlex"></span><span class="sect">§ 4.4</span></li>
<li class="hbox"><a href="#rhino">Rhino Support</a><span class="spacer boxFlex"></span><span class="sect">§ 4.5</span></li>
<li class="hbox"><a href="#nashorn">Nashorn Support</a><span class="spacer boxFlex"></span><span class="sect">§ 4.6</span></li>
<li class="hbox"><a href="#errors">Handling Errors</a><span class="spacer boxFlex"></span><span class="sect">§ 4.7</span></li>
</ul>
<li class="hbox"><a href="#plugins">Loader Plugins</a><span class="spacer boxFlex"></span><span class="sect">§§ 5-5.4</span></li>
<ul>
<li class="hbox"><a href="#text">Specify a Text File Dependency</a><span class="spacer boxFlex"></span><span class="sect">§ 5.1</span></li>
<li class="hbox"><a href="#pageload">Page Load Event Support/DOM Ready</a><span class="spacer boxFlex"></span><span class="sect">§ 5.2</span></li>
<li class="hbox"><a href="#i18n">Define an I18N Bundle</a><span class="spacer boxFlex"></span><span class="sect">§ 5.3</span></li>
</ul>
</ul>
</div>
<div class="section">
<h2>
<a href="#usage" name="usage">Usage</a>
<span class="sectionMark">§ 1</span>
</h2>
<h3>
<a href="#jsfiles" name="jsfiles">Load JavaScript Files</a>
<span class="sectionMark">§ 1.1</span>
</h3>
<p>RequireJS takes a different approach to script loading than traditional <script> tags. 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>
<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 <a href="#data-main">data-main attribute</a> 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>
<pre><code><!--This sets the baseUrl to the "scripts" directory, and
loads a script that will have a module ID of 'main'-->
<script data-main="scripts/main.js" src="scripts/require.js"></script>
</code></pre>
<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>
<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
up locations of a group of scripts. All of these capabilities allow you to use smaller strings for scripts as compared to traditional <script> tags.</p>
<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 characteristics, 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>
<ul>
<li>Ends in ".js".</li>
<li>Starts with a "/".</li>
<li>Contains an URL protocol, like "http:" or "https:".</li>
</ul>
<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>
<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>
<ul>
<li>www/
<ul>
<li>index.html</li>
<li>js/
<ul>
<li>app/
<ul>
<li>sub.js</li>
</ul>
</li>
<li>lib/
<ul>
<li>jquery.js</li>
<li>canvas.js</li>
</ul></li>
<li>app.js</li>
<li>require.js</li>
</ul></li>
</ul></li>
</ul>
<p>in index.html:</p>
<pre><code><script data-main="js/app.js" src="js/require.js"></script></code></pre>
<p>and in app.js:</p>
<pre><code>requirejs.config({
//By default load any module IDs from js/lib
baseUrl: 'js/lib',
//except, if the module ID starts with "app",
//load it from the js/app directory. paths
//config is relative to the baseUrl, and
//never includes a ".js" extension since
//the paths config could be for a directory.
paths: {
app: '../app'
}
});
// Start the main app logic.
requirejs(['jquery', 'canvas', 'app/sub'],
function ($, canvas, sub) {
//jQuery, canvas and the app/sub module are all
//loaded and can be used here now.
});
</code></pre>
<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>
<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>
<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>
<h3>
<a href="#data-main" name="data-main">data-main Entry Point</a>
<span class="sectionMark">§ 1.2</span>
</h3>
<p>The data-main attribute is a special attribute that require.js will check to start script loading:</p>
<pre><code><!--when require.js loads it will inject another script tag
(with async attribute) for scripts/main.js-->
<script data-main="scripts/main" src="scripts/require.js"></script>
</code></pre>
<p>You will typically use a data-main script to <a href="#config">set configuration options</a> and then load the first application module. Note: the script tag require.js generates for your data-main module includes the <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#attr-async">async attribute</a>. This means that <strong>you cannot assume that the load and execution of your data-main script will finish prior to other scripts referenced later in the same page.</strong></p>
<p>For example, this arrangement will fail randomly when the require.config path for the 'foo' module has not been set prior to it being require()'d later:</p>
<pre><code><script data-main="scripts/main" src="scripts/require.js"></script>
<script src="scripts/other.js"></script>
</code></pre>
<pre><code>// contents of main.js:
require.config({
paths: {
foo: 'libs/foo-1.1.3'
}
});
</code></pre>
<pre><code>// contents of other.js:
// This code might be called before the require.config() in main.js
// has executed. When that happens, require.js will attempt to
// load 'scripts/foo.js' instead of 'scripts/libs/foo-1.1.3.js'
require(['foo'], function(foo) {
});
</code></pre>
<p>If you want to do <code>require()</code> calls in the HTML page, then it is best to not use data-main. data-main is only intended for use when the page just has one main entry point, the data-main script. For pages that want to do inline <code>require()</code> calls, it is best to nest those inside a <code>require()</code> call for the configuration:</p>
<pre><code><script src="scripts/require.js"></script>
<script>
require(['scripts/config'], function() {
// Configuration loaded now, safe to do other require calls
// that depend on that config.
require(['foo'], function(foo) {
});
});
</script>
</code></pre>
<h3>
<a href="#define" name="define">Define a Module</a>
<span class="sectionMark">§ 1.3</span>
</h3>
<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>
<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>
<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>
<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>
<div class="subSection">
<h4>
<a href="#defsimple" name="defsimple">Simple Name/Value Pairs</a>
<span class="sectionMark">§ 1.3.1</span>
</h4>
<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>
<pre><code>//Inside file my/shirt.js:
define({
color: "black",
size: "unisize"
});
</code></pre>
</div>
<div class="subSection">
<h4>
<a href="#deffunc" name="deffunc">Definition Functions</a>
<span class="sectionMark">§ 1.3.2</span>
</h4>
<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>
<pre><code>//my/shirt.js now does setup work
//before returning its module definition.
define(function () {
//Do setup work here
return {
color: "black",
size: "unisize"
}
});
</code></pre>
</div>
<div href="#subSection" class="subSection">
<h4><a href="#defdep" name="defdep">Definition Functions with Dependencies</a><span class="sectionMark">§ 1.3.3</span></h4>
<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>
<pre><code>//my/shirt.js now has some dependencies, a cart and inventory
//module in the same directory as shirt.js
define(["./cart", "./inventory"], function(cart, inventory) {
//return an object to define the "my/shirt" module.
return {
color: "blue",
size: "large",
addToCart: function() {
inventory.decrement(this);
cart.add(this);
}
}
}
);
</code></pre>
<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>
<ul>
<li>my/cart.js</li>
<li>my/inventory.js</li>
<li>my/shirt.js</li>
</ul>
<p>The function call above specifies two arguments, "cart" and "inventory". These are the modules represented by the "./cart" and "./inventory" module names.</p>
<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>
<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>
<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>
</div>
<div class="subSection">
<h4><a href="#funcmodule" name="funcmodule">Define a Module as a Function</a><span class="sectionMark">§ 1.3.4</span></h4>
<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>
<pre><code>//A module definition inside foo/title.js. It uses
//my/cart and my/inventory modules from before,
//but since foo/title.js is in a different directory than
//the "my" modules, it uses the "my" in the module dependency
//name to find them. The "my" part of the name can be mapped
//to any directory, but by default, it is assumed to be a
//sibling to the "foo" directory.
define(["my/cart", "my/inventory"],
function(cart, inventory) {
//return a function to define "foo/title".
//It gets or sets the window title.
return function(title) {
return title ? (window.title = title) :
inventory.storeName + ' ' + cart.name;
}
}
);
</code></pre>
</div>
<div class="subSection">
<h4><a href="#cjsmodule" name="cjsmodule">Define a Module with Simplified CommonJS Wrapper</a><span class="sectionMark">§ 1.3.5</span></h4>
<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
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>
<pre><code>define(function(require, exports, module) {
var a = require('a'),
b = require('b');
//Return the module value
return function () {};
}
);
</code></pre>
<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>
<p>More information is available on the <a href="commonjs.html">CommonJS page</a>, and in the <a href="whyamd.html#sugar">"Sugar" section in the Why AMD page</a>.
</div>
<div class="subSection">
<h4><a href="#modulename" name="modulename">Define a Module with a Name</a><span class="sectionMark">§ 1.3.6</span></h4>
<p>You may encounter some define() calls that include a name for the module as the first argument to define():</p>
<pre><code> //Explicitly defines the "foo/title" module:
define("foo/title",
["my/cart", "my/inventory"],
function(cart, inventory) {
//Define foo/title object in here.
}
);
</code></pre>
<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>
</div>
<div class="subSection">
<h4><a href="#modulenotes" name="modulenotes">Other Module Notes</a><span class="sectionMark">§ 1.3.7</span></h4>
<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. You should only use the <a href="optimization.html">optimization tool</a> to group multiple modules into optimized files.</p>
<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>
<pre><code>define(["require", "./relative/name"], function(require) {
var mod = require("./relative/name");
});
</code></pre>
<p>Or better yet, use the shortened syntax that is available for use with <a href="commonjs.html">translating CommonJS</a> modules:</p>
<pre><code>define(function(require) {
var mod = require("./relative/name");
});
</code></pre>
<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>
<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
having to know the directory's name.</p>
<p id="modulenotes-relative-names"><strong>Relative module names are relative to other names, not paths</strong>: The loader stores modules by their name and not by their path internally. So for relative name references, those are resolved relative to the module name making the reference, then that module name, or ID, is converted to a path if needs to be loaded. Example code for a 'compute' package that has a 'main' and 'extras' modules in it:</p>
<pre><code>* lib/
* compute/
* main.js
* extras.js
</code></pre>
<p>where the main.js module looks like this:</p>
<pre><code>define(["./extras"], function(extras) {
//Uses extras in here.
});
</code></pre>
<p>If this was the paths config:</p>
<pre><code>require.config({
baseUrl: 'lib',
paths: {
'compute': 'compute/main'
}
});
</code></pre>
<p>And a <code>require(['compute'])</code> is done, then lib/compute/main.js will have the module name of 'compute'. When it asks for './extras', that is resolved relative to 'compute', so 'compute/./extras', which normalizes to just 'extras'. Since there is no paths config for that module name, the path generated will be for 'lib/extras.js', which is incorrect.</p>
<p>For this case, <a href="#packages">packages config</a> is a better option, since it allows setting the main module up as 'compute', but internally the loader will store the module with the ID of 'compute/main' so that the relative reference for './extras' works.</p>
<p>Another option is to construct a module at lib/compute.js that is just <code>define(['./compute/main'], function(m) { return m; });</code>, then there is no need for paths or packages config.</p>
<p>Or, do not set that paths or packages config and do the top level require call as <code>require(['compute/main'])</code>.</p>
<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>
<pre><code>define(["require"], function(require) {
var cssUrl = require.toUrl("./style.css");
});
</code></pre>
<p id="modulenotes-console"><strong>Console debugging</strong>: If you need to work with a module you already loaded via a <code>require(["module/name"], function(){})</code> 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>
<pre><code>require("module/name").callSomeFunction()
</code></pre>
<p>Note this only works if "module/name" was previously loaded via the async version of require: <code>require(["module/name"])</code>. If using a relative path, like './module/name', those only work inside define</p>
</div>
<div class="subSection">
<h4><a href="#circular" name="circular">Circular Dependencies</a><span class="sectionMark">§ 1.3.8</span></h4>
<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>
<pre><code>//Inside b.js:
define(["require", "a"],
function(require, a) {
//"a" in this case will be null if "a" also asked for "b",
//a circular dependency.
return function(title) {
return require("a").doSomething();
}
}
);
</code></pre>
<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>
<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>
<pre><code>//Inside b.js:
define(function(require, exports, module) {
//If "a" has used exports, then we have a real
//object reference here. However, we cannot use
//any of "a"'s properties until after "b" returns a value.
var a = require("a");
exports.foo = function () {
return a.bar();
};
});
</code></pre>
<p>Or, if you are using the dependency array approach, ask for the special
<a href="https://github.com/requirejs/requirejs/wiki/Differences-between-the-simplified-CommonJS-wrapper-and-standard-AMD-define#wiki-magic">'exports' dependency:</a></p>
<pre><code>//Inside b.js:
define(['a', 'exports'], function(a, exports) {
//If "a" has used exports, then we have a real
//object reference here. However, we cannot use
//any of "a"'s properties until after "b" returns a value.
exports.foo = function () {
return a.bar();
};
});
</code></pre>
</div>
<div class="subSection">
<h4><a href="#jsonp" name="jsonp">Specify a JSONP Service Dependency</a><span class="sectionMark">§ 1.3.9</span></h4>
<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>
<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>
<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>
<pre><code>require(["http://example.com/api/data.json?callback=define"],
function (data) {
//The data object will be the API response for the
//JSONP data call.
console.log(data);
}
);
</code></pre>
<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>
<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>
<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>
<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>
</div>
<div class="subSection">
<h4><a href="#undef" name="undef">Undefining a Module</a><span class="sectionMark">§ 1.3.10</span></h4>
<p>There is a global function, <b>requirejs.undef()</b>, that allows undefining a module. It will reset the
loader's internal state to forget about the previous definition of the module.</p>
<p><b>However</b>, it will not remove the module from other modules that are already defined and got a
handle on that module as a dependency when they executed. So it is really only useful to use in
error situations when no other modules have gotten a handle on a module value, or as part of any future
module loading that may use that module. See the <a href="#errbacks">errback section</a> for an example.</p>
<p>If you want to do more sophisticated dependency graph analysis for undefining work, the semi-private
<a href="https://github.com/requirejs/requirejs/wiki/Internal-API:-onResourceLoad">onResourceLoad API</a> may be helpful.</p>
</div>
</div>
<div class="section">
<h2>
<a href="#mechanics" name="mechanics">Mechanics</a>
<span class="sectionMark">§ 2</span>
</h2>
<p>RequireJS loads each dependency as a script tag, using head.appendChild().</p>
<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 once the dependencies for those functions have been called. Note that the dependencies for a given module definition function could be called in any order, due to their sub-dependency relationships and network load order.</p>
<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>
<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>
</div>
<div class="section">
<h2>
<a href="#config" name="config">Configuration Options</a>
<span class="sectionMark">§ 3</span>
</h2>
<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>
<pre><code><script src="scripts/require.js"></script>
<script>
require.config({
baseUrl: "/another/path",
paths: {
"some": "some/v1.0"
},
waitSeconds: 15
});
require( ["some/module", "my/module", "a.js", "b.js"],
function(someModule, myModule) {
//This function will be called when all the dependencies
//listed above are loaded. Note that this function could
//be called before the page is loaded.
//This callback is optional.
}
);
</script>
</code></pre>
<p>You may also call require.config from your <a href="api.html#data-main">data-main Entry Point</a>, but be aware that the data-main script is loaded asynchronously. Avoid other entry point scripts which wrongly assume that data-main and its require.config will always execute prior to their script loading.</a></p>
<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.
This example specifies some dependencies to load as soon as require.js defines require():</p>
<pre><code><script>
var require = {
deps: ["some/module1", "my/module2", "a.js", "b.js"],
callback: function(module1, module2) {
//This function will be called when all the dependencies
//listed above in deps are loaded. Note that this
//function could be called before the page is loaded.
//This callback is optional.
}
};
</script>
<script src="scripts/require.js"></script>
</code></pre>
<p><b>Note:</b> It is best to use <code>var require = {}</code> and do not use
<code>window.require = {}</code>, it will not behave correctly in IE.</p>
<p>There are <a href="https://github.com/requirejs/requirejs/wiki/Patterns-for-separating-config-from-the-main-module">some patterns for separating the config from main module loading</a>.</p>
<p>Supported configuration options:</p>
<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>
<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>
<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>
<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>
<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>
<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>
<p id="config-bundles"><strong><a href="#config-bundles">bundles</a></strong>: Introduced in RequireJS 2.1.10: allows configuring multiple module IDs to be found in another script. Example:</p>
<pre><code>requirejs.config({
bundles: {
'primary': ['main', 'util', 'text', 'text!template.html'],
'secondary': ['text!secondary.html']
}
});
require(['util', 'text'], function(util, text) {
//The script for module ID 'primary' was loaded,
//and that script included the define()'d
//modules for 'util' and 'text'
});
</code></pre>
<p>That config states: modules 'main', 'util', 'text' and 'text!template.html' will be found by loading module ID 'primary'. Module 'text!secondary.html' can be found by loading module ID 'secondary'.
</p>
<p>This only sets up where to find a module inside a script that has multiple define()'d modules in it. It does not automatically bind those modules to the bundle's module ID. The bundle's module ID is just used for locating the set of modules.</p>
<p>Something similar is possible with paths config, but it is much wordier, and the paths config route does not allow loader plugin resource IDs in its configuration, since the paths config values are path segments, not IDs.</p>
<p>bundles config is useful if doing a build and that build target was not an existing module ID, or if you have loader plugin resources in built JS files that should not be loaded by the loader plugin. <strong>Note that the keys and values are module IDs</strong>, not path segments. They are absolute module IDs, not a module ID prefix like <a href="#config-paths">paths config</a> or <a href="#config-map">map config</a>. Also, bundle config is different from map config in that map config is a one-to-one module ID relationship, where bundle config is for pointing multiple module IDs to a bundle's module ID.</p>
<p>As of RequireJS 2.2.0, the optimizer can generate the bundles config and insert it into the top level requirejs.config() call. See the <a href="https://github.com/requirejs/r.js/blob/98a9949480d68a781c8d6fc4ce0a07c16a2c8a2a/build/example.build.js#L641">bundlesConfigOutFile</a> build config option for more details.</p>
<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>
<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>
<pre><code>requirejs.config({
//Remember: only use shim config for non-AMD scripts,
//scripts that do not already call define(). The shim
//config will not work correctly if used on AMD scripts,
//in particular, the exports and init config will not
//be triggered, and the deps config will be confusing
//for those cases.
shim: {
'backbone': {
//These script dependencies should be loaded before loading
//backbone.js
deps: ['underscore', 'jquery'],
//Once loaded, use the global 'Backbone' as the
//module value.
exports: 'Backbone'
},
'underscore': {
exports: '_'
},
'foo': {
deps: ['bar'],
exports: 'Foo',
init: function (bar) {
//Using a function allows you to call noConflict for
//libraries that support it, and do other cleanup.
//However, plugins for those libraries may still want
//a global. "this" for the function will be the global
//object. The dependencies will be passed in as
//function arguments. If this function returns a value,
//then that value is used as the module export value
//instead of the object found via the 'exports' string.
//Note: jQuery registers as an AMD module via define(),
//so this will not work for jQuery. See notes section
//below for an approach for jQuery.
return this.Foo.noConflict();
}
}
}
});
//Then, later in a separate file, call it 'MyModel.js', a module is
//defined, specifying 'backbone' as a dependency. RequireJS will use
//the shim config to properly load 'backbone' and give a local
//reference to this module. The global Backbone will still exist on
//the page too.
define(['backbone'], function (Backbone) {
return Backbone.Model.extend({});
});
</code></pre>
<p>In RequireJS 2.0.*, the "exports" property in the shim config could have
been a function instead of a string. In that case, it functioned
the same as the "init" property as shown above. The "init" pattern is used in
RequireJS 2.1.0+ so a string value for <code>exports</code> can be used for
<a href="#config-enforceDefine">enforceDefine</a>, but then allow
functional work once the library is known to have loaded.</p>
<p>For "modules" that are just jQuery or Backbone plugins that do not need to export
any module value, the shim config can just be an array of dependencies:</p>
<pre><code>requirejs.config({
shim: {
'jquery.colorize': ['jquery'],
'jquery.scroll': ['jquery'],
'backbone.layoutmanager': ['backbone']
}
});
</code></pre>
<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
loaded (a return from init is <strong>not</strong> used for <code>enforceDefine</code> checking):</p>
<pre><code>requirejs.config({
shim: {
'jquery.colorize': {
deps: ['jquery'],
exports: 'jQuery.fn.colorize'
},
'jquery.scroll': {
deps: ['jquery'],
exports: 'jQuery.fn.scroll'
},
'backbone.layoutmanager': {
deps: ['backbone']
exports: 'Backbone.LayoutManager'
}
}
});
</code></pre>
<p><b>Important notes for "shim" config:</b></p>
<ul>
<li>The shim config only sets up code relationships. To load modules that
are part of or use shim config, a normal require/define call is needed. Setting shim by
itself does not trigger code to load.</li>
<li>Only use other "shim" modules as dependencies for shimmed scripts, or
AMD libraries that have no dependencies and call define() after they also
create a global (like jQuery or lodash). Otherwise, if you use an AMD
module as a dependency for a shim config module, after a build, that
AMD module may not be evaluated until after the shimmed code in the build
executes, and an error will occur. The ultimate fix is to upgrade all the
shimmed code to have optional AMD define() calls.</li>
<li>If it is not possible to upgrade the shimmed code to use AMD define()
calls, as of RequireJS 2.1.11, the optimizer has a
<a href="https://github.com/requirejs/r.js/blob/b8a6982d2923ae8389355edaa50d2b7f8065a01a/build/example.build.js#L68">wrapShim build option</a> that will
try to automatically wrap the shimmed code in a define() for a build. This
changes the scope of shimmed dependencies, so it is not guaranteed to always
work, but, for example, for shimmed dependencies that depend on an AMD version of Backbone,
it can be helpful.</li>
<li>The init function will <strong>not</strong> be called for AMD modules.
For example, you cannot use a shim init function to call jQuery's noConflict.
See <a href="jquery.html#noconflictmap">Mapping Modules to use noConflict</a>
for an alternate approach to jQuery.</li>
<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>
</ul>
<p><b>Important optimizer notes for "shim" config</b>:</p>
<ul>
<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>
<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>
<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>
<li>If you are using uglifyjs to minify the code, <strong>do not</strong> set the uglify
option <code>toplevel</code> to true, or if using the command line
<strong>do not</strong> pass <code>-mt</code>. That option mangles
the global names that shim uses to find exports.</li>
</ul>
<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>
<p>This sort of capability is really important for larger projects which may have
two sets of modules that need to use two different versions of 'foo', but they
still need to cooperate with each other.</p>
<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>
<p>map example:</p>
<pre><code>requirejs.config({
map: {
'some/newmodule': {
'foo': 'foo1.2'
},
'some/oldmodule': {
'foo': 'foo1.0'
}
}
});
</code></pre>
<p>If the modules are laid out on disk like this:</p>
<ul>
<li>foo1.0.js</li>
<li>foo1.2.js</li>
<li>some/
<ul>
<li>newmodule.js</li>
<li>oldmodule.js</li>
</ul>
</li>
</ul>
<p>When 'some/newmodule' does `require('foo')` it will get the foo1.2.js file,
and when 'some/oldmodule' does `require('foo')` it will get the foo1.0.js file.</p>
<p>This feature only works well for scripts that are real AMD modules that call
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>
<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>
<pre><code>
requirejs.config({
map: {
'*': {
'foo': 'foo1.2'
},
'some/oldmodule': {
'foo': 'foo1.0'
}
}
});
</code></pre>
<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>
<p id="config-map-notes"><strong>Note:</strong> when doing builds with map config, the map config needs to be fed to the optimizer, and the build output must still contain a requirejs config call that sets up the map config. The optimizer does not do ID renaming during the build, because some dependency references in a project could depend on runtime variable state. So the optimizer does not invalidate the need for a map config after the build.</p>
<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>
<pre><code>requirejs.config({
config: {
'bar': {
size: 'large'
},
'baz': {
color: 'blue'
}
}
});
//bar.js, which uses simplified CJS wrapping:
//https://requirejs.org/docs/whyamd.html#sugar
define(function (require, exports, module) {
//Will be the value 'large'
var size = module.config().size;
});
//baz.js which uses a dependency array,
//it asks for the special module ID, 'module':
//https://github.com/requirejs/requirejs/wiki/Differences-between-the-simplified-CommonJS-wrapper-and-standard-AMD-define#wiki-magic
define(['module'], function (module) {
//Will be the value 'blue'
var color = module.config().color;
});
</code></pre>
<p>For passing config to a <a href="#packages">package</a>, target the main module in the package,
not the package ID:</p>
<pre><code>requirejs.config({
//Pass an API key for use in the pixie package's
//main module.
config: {
'pixie/index': {
apiKey: 'XJKDLNS'
}
},
//Set up config for the "pixie" package, whose main
//module is the index.js file in the pixie folder.
packages: [
{
name: 'pixie',
main: 'index'
}
]
});
</code></pre>
<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>
<p id="config-nodeIdCompat"><strong><a href="#config-nodeIdCompat">nodeIdCompat</a></strong>: Node treats module ID <code>example.js</code> and <code>example</code> the same. By default these are two different IDs in RequireJS. If you end up using modules installed from npm, then you may need to set this config value to <code>true</code> to avoid resolution issues. This option only applies to treating the ".js" suffix differently, it does not do any other node resolution and evaluation matching such as .json file handling (JSON handling needs a 'json!' loader plugin anyway). Available in 2.1.10 and greater.</p>
<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>
<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>
<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>
any other require() calls from starting their requests for modules, it is just a way to specify
some modules to load asynchronously as part of a config block.</p>
<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>
<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>
<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>
<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>
<pre><code>urlArgs: "bust=" + (new Date()).getTime()
</code></pre>
<p>As of RequireJS 2.2.0, urlArgs can be a function. If a function, it will receive the module ID and the URL as parameters, and it should return a string that will be added to the end of the URL. Return an empty string if no args. Be sure to take care of adding the '?' or '&' depending on the existing state of the URL. Example:</p>
<pre><code>requirejs.config({
urlArgs: function(id, url) {
var args = 'v=1';
if (url.indexOf('view.html') !== -1) {
args = 'v=2'
}
return (url.indexOf('?') === -1 ? '?' : '&') + args;
}
});
</code></pre>
<p>During development it can be useful to use this, however <strong>be sure</strong> to remove it before deploying your code.</p>
<p id="config-scriptType"><strong><a href="#config-scriptType">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>
<p id="config-skipDataMain"><strong><a href="#config-skipDataMain">skipDataMain</a></strong>: Introduced in RequireJS 2.1.9: If set to <code>true</code>, skips the <a href="#data-main">data-main attribute scanning</a> done to start module loading. Useful if RequireJS is embedded in a utility library that may interact with other RequireJS library on the page, and the embedded version should not do data-main loading.</p>
</div>
<div class="section">
<h2>
<a href="#advanced" name="advanced">Advanced Usage</a>
<span class="sectionMark">§ 4</span>
</h2>
<h3><a href="#packages" name="packages">Loading Modules from Packages</a><span class="sectionMark">§ 4.1</span></h3>
<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>
<ul>
<li>A package can be associated with a module name/prefix.</li>
<li>The package config can specify the following properties for a specific package:
<ul>
<li><strong>name</strong>: The name of the package (used for the module name/prefix mapping)</li>
<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>
<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>
</ul></li>
</ul>
<p><strong>IMPORTANT NOTES</strong></p>
<ul>
<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>
<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>
</ul>
<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>
<ul>
<li>project-directory/
<ul>
<li>project.html</li>
<li>scripts/
<ul>
<li>require.js</li>
</ul></li>
</ul></li>
</ul>
<p>Here is how the example directory layout looks with two packages, <strong>cart</strong> and <strong>store</strong>:</p>
<ul>
<li>project-directory/
<ul>
<li>project.html</li>
<li>scripts/
<ul>
<li>cart/
<ul>
<li>main.js</li>
</ul></li>
<li>store/
<ul>
<li>main.js</li>
<li>util.js</li>
</ul></li>
<li>main.js</li>
<li>require.js</li>
</ul></li>
</ul></li>
</ul>
<p><strong>project.html</strong> will have a script tag like this:</p>
<pre><code><script data-main="scripts/main" src="scripts/require.js"></script>
</code></pre>
<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>
<pre><code>//main.js contents
//Pass a config object to require
require.config({
"packages": ["cart", "store"]
});
require(["cart", "store", "store/util"],
function (cart, store, util) {
//use the modules as usual.
});
</code></pre>
<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>
<p>If the "store" package did not follow the "main.js" convention, and looked more like this:</p>
<ul>
<li>project-directory/
<ul>
<li>project.html</li>