PageRenderTime 61ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/app/components/requirejs/docs/api.html

https://bitbucket.org/reidstackwave/front-end-template
HTML | 1222 lines | 948 code | 274 blank | 0 comment | 0 complexity | 0add9f0cc8ae15f3a51ce7daf6bb69f1 MD5 | raw file
Possible License(s): GPL-2.0, Apache-2.0, BSD-3-Clause

Large files files are truncated, but you can click here to view the full file

  1. <div id="directory" class="section">
  2. <h1>RequireJS API</h1>
  3. <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>
  4. <ul class="index mono">
  5. <li class="hbox"><a href="#usage">Usage</a><span class="spacer boxFlex"></span><span class="sect">&sect;&sect; 1-1.2</span></li>
  6. <ul>
  7. <li class="hbox"><a href="#jsfiles">Load JavaScript Files</a><span class="spacer boxFlex"></span><span class="sect">&sect; 1.1</span></li>
  8. <li class="hbox"><a href="#define">Define a Module</a><span class="spacer boxFlex"></span><span class="sect">&sect; 1.2</span></li>
  9. <ul>
  10. <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>
  11. <li class="hbox"><a href="#deffunc">Definition Functions</a><span class="spacer boxFlex"></span><span class="sect">&sect; 1.2.2</span></li>
  12. <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>
  13. <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>
  14. <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>
  15. <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>
  16. <li class="hbox"><a href="#modulenotes">Other Module Notes</a><span class="spacer boxFlex"></span><span class="sect">&sect; 1.2.7</span></li>
  17. <li class="hbox"><a href="#circular">Circular Dependencies</a><span class="spacer boxFlex"></span><span class="sect">&sect; 1.2.8</span></li>
  18. <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>
  19. <li class="hbox"><a href="#undef">Undefining a Module</a><span class="spacer boxFlex"></span><span class="sect">&sect; 1.2.10</span></li>
  20. </ul>
  21. </ul>
  22. <li class="hbox"><a href="#mechanics">Mechanics</a><span class="spacer boxFlex"></span><span class="sect">&sect;&sect; 2</span></li>
  23. <li class="hbox"><a href="#config">Configuration Options</a><span class="spacer boxFlex"></span><span class="sect">&sect;&sect; 3</span></li>
  24. <li class="hbox"><a href="#advanced">Advanced Usage</a><span class="spacer boxFlex"></span><span class="sect">&sect;&sect; 4-4.6</span></li>
  25. <ul>
  26. <li class="hbox"><a href="#packages">Loading Modules from Packages</a><span class="spacer boxFlex"></span><span class="sect">&sect; 4.1</span></li>
  27. <li class="hbox"><a href="#multiversion">Multiversion Support</a><span class="spacer boxFlex"></span><span class="sect">&sect; 4.2</span></li>
  28. <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>
  29. <li class="hbox"><a href="#webworker">Web Worker Support</a><span class="spacer boxFlex"></span><span class="sect">&sect; 4.4</span></li>
  30. <li class="hbox"><a href="#rhino">Rhino Support</a><span class="spacer boxFlex"></span><span class="sect">&sect; 4.5</span></li>
  31. <li class="hbox"><a href="#errors">Handling Errors</a><span class="spacer boxFlex"></span><span class="sect">&sect; 4.6</span></li>
  32. </ul>
  33. <li class="hbox"><a href="#plugins">Loader Plugins</a><span class="spacer boxFlex"></span><span class="sect">&sect;&sect; 5-5.4</span></li>
  34. <ul>
  35. <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>
  36. <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>
  37. <li class="hbox"><a href="#i18n">Define an I18N Bundle</a><span class="spacer boxFlex"></span><span class="sect">&sect; 5.3</span></li>
  38. </ul>
  39. </ul>
  40. </div>
  41. <div class="section">
  42. <h2>
  43. <a href="#usage" name="usage">Usage</a>
  44. <span class="sectionMark">&sect; 1</span>
  45. </h2>
  46. <h3>
  47. <a href="#jsfiles" name="jsfiles">Load JavaScript Files</a>
  48. <span class="sectionMark">&sect; 1.1</span>
  49. </h3>
  50. <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>
  51. <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>
  52. <pre><code>&lt;!--This sets the baseUrl to the "scripts" directory, and
  53. loads a script that will have a module ID of 'main'--&gt;
  54. &lt;script data-main="scripts/main.js" src="scripts/require.js"&gt;&lt;/script&gt;
  55. </code></pre>
  56. <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>
  57. <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
  58. 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>
  59. <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>
  60. <ul>
  61. <li>Ends in ".js".</li>
  62. <li>Starts with a "/".</li>
  63. <li>Contains an URL protocol, like "http:" or "https:".</li>
  64. </ul>
  65. <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>
  66. <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 form your app code, use a directory layout like this:</p>
  67. <ul>
  68. <li>www/
  69. <ul>
  70. <li>index.html</li>
  71. <li>js/
  72. <ul>
  73. <li>app/
  74. <ul>
  75. <li>sub.js</li>
  76. </ul>
  77. </li>
  78. <li>lib/
  79. <ul>
  80. <li>jquery.js</li>
  81. <li>canvas.js</li>
  82. </ul></li>
  83. <li>app.js</li>
  84. </ul></li>
  85. </ul></li>
  86. </ul>
  87. <p>in index.html:</p>
  88. <pre><code>&lt;script data-main="js/app.js" src="js/require.js"&gt;&lt;/script&gt;</code></pre>
  89. <p>and in app.js:</p>
  90. <pre><code>requirejs.config({
  91. //By default load any module IDs from js/lib
  92. baseUrl: 'js/lib',
  93. //except, if the module ID starts with "app",
  94. //load it from the js/app directory. paths
  95. //config is relative to the baseUrl, and
  96. //never includes a ".js" extension since
  97. //the paths config could be for a directory.
  98. paths: {
  99. app: '../app'
  100. }
  101. });
  102. // Start the main app logic.
  103. requirejs(['jquery', 'canvas', 'app/sub'],
  104. function ($, canvas, sub) {
  105. //jQuery, canvas and the app/sub module are all
  106. //loaded and can be used here now.
  107. });
  108. </code></pre>
  109. <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>
  110. <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>
  111. <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>
  112. <h3>
  113. <a href="#define" name="define">Define a Module</a>
  114. <span class="sectionMark">&sect; 1.2</span>
  115. </h3>
  116. <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>
  117. <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>
  118. <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>
  119. <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>
  120. <div class="subSection">
  121. <h4>
  122. <a href="#defsimple" name="defsimple">Simple Name/Value Pairs</a>
  123. <span class="sectionMark">&sect; 1.2.1</span>
  124. </h4>
  125. <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>
  126. <pre><code>//Inside file my/shirt.js:
  127. define({
  128. color: "black",
  129. size: "unisize"
  130. });
  131. </code></pre>
  132. </div>
  133. <div class="subSection">
  134. <h4>
  135. <a href="#deffunc" name="deffunc">Definition Functions</a>
  136. <span class="sectionMark">&sect; 1.2.2</span>
  137. </h4>
  138. <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>
  139. <pre><code>//my/shirt.js now does setup work
  140. //before returning its module definition.
  141. define(function () {
  142. //Do setup work here
  143. return {
  144. color: "black",
  145. size: "unisize"
  146. }
  147. });
  148. </code></pre>
  149. </div>
  150. <div href="#subSection" class="subSection">
  151. <h4><a href="#defdep" name="defdep">Definition Functions with Dependencies</a><span class="sectionMark">&sect; 1.2.3</span></h4>
  152. <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>
  153. <pre><code>//my/shirt.js now has some dependencies, a cart and inventory
  154. //module in the same directory as shirt.js
  155. define(["./cart", "./inventory"], function(cart, inventory) {
  156. //return an object to define the "my/shirt" module.
  157. return {
  158. color: "blue",
  159. size: "large",
  160. addToCart: function() {
  161. inventory.decrement(this);
  162. cart.add(this);
  163. }
  164. }
  165. }
  166. );
  167. </code></pre>
  168. <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>
  169. <ul>
  170. <li>my/cart.js</li>
  171. <li>my/inventory.js</li>
  172. <li>my/shirt.js</li>
  173. </ul>
  174. <p>The function call above specifies two arguments, "cart" and "inventory". These are the modules represented by the "./cart" and "./inventory" module names.</p>
  175. <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>
  176. <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>
  177. <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>
  178. </div>
  179. <div class="subSection">
  180. <h4><a href="#funcmodule" name="funcmodule">Define a Module as a Function</a><span class="sectionMark">&sect; 1.2.4</span></h4>
  181. <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>
  182. <pre><code>//A module definition inside foo/title.js. It uses
  183. //my/cart and my/inventory modules from before,
  184. //but since foo/bar.js is in a different directory than
  185. //the "my" modules, it uses the "my" in the module dependency
  186. //name to find them. The "my" part of the name can be mapped
  187. //to any directory, but by default, it is assumed to be a
  188. //sibling to the "foo" directory.
  189. define(["my/cart", "my/inventory"],
  190. function(cart, inventory) {
  191. //return a function to define "foo/title".
  192. //It gets or sets the window title.
  193. return function(title) {
  194. return title ? (window.title = title) :
  195. inventory.storeName + ' ' + cart.name;
  196. }
  197. }
  198. );
  199. </code></pre>
  200. </div>
  201. <div class="subSection">
  202. <h4><a href="#cjsmodule" name="cjsmodule">Define a Module with Simplified CommonJS Wrapper</a><span class="sectionMark">&sect; 1.2.5</span></h4>
  203. <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
  204. 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>
  205. <pre><code>define(function(require, exports, module) {
  206. var a = require('a'),
  207. b = require('b');
  208. //Return the module value
  209. return function () {};
  210. }
  211. );
  212. </code></pre>
  213. <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>
  214. <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>.
  215. </div>
  216. <div class="subSection">
  217. <h4><a href="#modulename" name="modulename">Define a Module with a Name</a><span class="sectionMark">&sect; 1.2.6</span></h4>
  218. <p>You may encounter some define() calls that include a name for the module as the first argument to define():</p>
  219. <pre><code> //Explicitly defines the "foo/title" module:
  220. define("foo/title",
  221. ["my/cart", "my/inventory"],
  222. function(cart, inventory) {
  223. //Define foo/title object in here.
  224. }
  225. );
  226. </code></pre>
  227. <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>
  228. </div>
  229. <div class="subSection">
  230. <h4><a href="#modulenotes" name="modulenotes">Other Module Notes</a><span class="sectionMark">&sect; 1.2.7</span></h4>
  231. <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>
  232. <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>
  233. <pre><code>define(["require", "./relative/name"], function(require) {
  234. var mod = require("./relative/name");
  235. });
  236. </code></pre>
  237. <p>Or better yet, use the shortened syntax that is available for use with <a href="commonjs.html">translating CommonJS</a> modules:</p>
  238. <pre><code>define(function(require) {
  239. var mod = require("./relative/name");
  240. });
  241. </code></pre>
  242. <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>
  243. <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
  244. having to know the directory's name.</p>
  245. <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>
  246. <pre><code>define(["require"], function(require) {
  247. var cssUrl = require.toUrl("./style.css");
  248. });
  249. </code></pre>
  250. <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>
  251. <pre><code>require("module/name").callSomeFunction()
  252. </code></pre>
  253. <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>
  254. </div>
  255. <div class="subSection">
  256. <h4><a href="#circular" name="circular">Circular Dependencies</a><span class="sectionMark">&sect; 1.2.8</span></h4>
  257. <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>
  258. <pre><code>//Inside b.js:
  259. define(["require", "a"],
  260. function(require, a) {
  261. //"a" in this case will be null if a also asked for b,
  262. //a circular dependency.
  263. return function(title) {
  264. return require("a").doSomething();
  265. }
  266. }
  267. );
  268. </code></pre>
  269. <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>
  270. <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>
  271. <pre><code>//Inside b.js:
  272. define(function(require, exports, module) {
  273. //If "a" has used exports, then we have a real
  274. //object reference here. However, we cannot use
  275. //any of a's properties until after b returns a value.
  276. var a = require("a");
  277. exports.foo = function () {
  278. return a.bar();
  279. };
  280. });
  281. </code></pre>
  282. <p>Or, if you are using the dependency array approach, ask for the special
  283. <a href="https://github.com/jrburke/requirejs/wiki/Differences-between-the-simplified-CommonJS-wrapper-and-standard-AMD-define#wiki-magic">'exports' dependency:</a></p>
  284. <pre><code>//Inside b.js:
  285. define(['a', 'exports'], function(a, exports) {
  286. //If "a" has used exports, then we have a real
  287. //object reference here. However, we cannot use
  288. //any of a's properties until after b returns a value.
  289. exports.foo = function () {
  290. return a.bar();
  291. };
  292. });
  293. </code></pre>
  294. </div>
  295. <div class="subSection">
  296. <h4><a href="#jsonp" name="jsonp">Specify a JSONP Service Dependency</a><span class="sectionMark">&sect; 1.2.9</span></h4>
  297. <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>
  298. <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>
  299. <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>
  300. <pre><code>require(["http://example.com/api/data.json?callback=define"],
  301. function (data) {
  302. //The data object will be the API response for the
  303. //JSONP data call.
  304. console.log(data);
  305. }
  306. );
  307. </code></pre>
  308. <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>
  309. <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>
  310. <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>
  311. <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>
  312. </div>
  313. <div class="subSection">
  314. <h4><a href="#undef" name="undef">Undefining a Module</a><span class="sectionMark">&sect; 1.2.10</span></h4>
  315. <p>There is a global function, <b>requirejs.undef()</b>, that allows undefining a module. It will reset the
  316. loader's internal state to forget about the previous definition of the module.</p>
  317. <p><b>However</b>, it will not remove the module from other modules that are already defined and got a
  318. handle on that module as a dependency when they executed. So it is really only useful to use in
  319. error situations when no other modules have gotten a handle on a module value, or as part of any future
  320. module loading that may use that module. See the <a href="#errbacks">errback section</a> for an example.</p>
  321. <p>If you want to do more sophisticated dependency graph analysis for undefining work, the semi-private
  322. <a href="https://github.com/jrburke/requirejs/wiki/Internal-API:-onResourceLoad">onResourceLoad API</a> may be helpful.</p>
  323. </div>
  324. </div>
  325. <div class="section">
  326. <h2>
  327. <a href="#mechanics" name="mechanics">Mechanics</a>
  328. <span class="sectionMark">&sect; 2</span>
  329. </h2>
  330. <p>RequireJS loads each dependency as a script tag, using head.appendChild().</p>
  331. <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>
  332. <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>
  333. <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>
  334. </div>
  335. <div class="section">
  336. <h2>
  337. <a href="#config" name="config">Configuration Options</a>
  338. <span class="sectionMark">&sect; 3</span>
  339. </h2>
  340. <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>
  341. <pre><code>&lt;script src="scripts/require.js"&gt;&lt;/script&gt;
  342. &lt;script&gt;
  343. require.config({
  344. baseUrl: "/another/path",
  345. paths: {
  346. "some": "some/v1.0"
  347. },
  348. waitSeconds: 15
  349. });
  350. require( ["some/module", "my/module", "a.js", "b.js"],
  351. function(someModule, myModule) {
  352. //This function will be called when all the dependencies
  353. //listed above are loaded. Note that this function could
  354. //be called before the page is loaded.
  355. //This callback is optional.
  356. }
  357. );
  358. &lt;/script&gt;
  359. </code></pre>
  360. <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.
  361. This example specifies some dependencies to load as soon as require.js defines require():</p>
  362. <pre><code>&lt;script&gt;
  363. var require = {
  364. deps: ["some/module1", "my/module2", "a.js", "b.js"],
  365. callback: function(module1, module2) {
  366. //This function will be called when all the dependencies
  367. //listed above in deps are loaded. Note that this
  368. //function could be called before the page is loaded.
  369. //This callback is optional.
  370. }
  371. };
  372. &lt;/script&gt;
  373. &lt;script src="scripts/require.js"&gt;&lt;/script&gt;
  374. </code></pre>
  375. <p><b>Note:</b> It is best to use <code>var require = {}</code> and do not use
  376. <code>window.require = {}</code>, it will not behave correctly in IE.</p>
  377. <p>Supported configuration options:</p>
  378. <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>
  379. <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>
  380. <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>
  381. <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>
  382. <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>
  383. <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>
  384. <p id="config-shim"><strong><a href="#config-shim">shim</a></strong>: Configure the dependencies and exports for older, traditional "browser globals" scripts that do not use define() to declare the dependencies and set a module value.</p>
  385. <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>
  386. <pre><code>requirejs.config({
  387. shim: {
  388. 'backbone': {
  389. //These script dependencies should be loaded before loading
  390. //backbone.js
  391. deps: ['underscore', 'jquery'],
  392. //Once loaded, use the global 'Backbone' as the
  393. //module value.
  394. exports: 'Backbone'
  395. },
  396. 'underscore': {
  397. exports: '_'
  398. },
  399. 'foo': {
  400. deps: ['bar'],
  401. exports: 'Foo',
  402. init: function (bar) {
  403. //Using a function allows you to call noConflict for
  404. //libraries that support it, and do other cleanup.
  405. //However, plugins for those libraries may still want
  406. //a global. "this" for the function will be the global
  407. //object. The dependencies will be passed in as
  408. //function arguments. If this function returns a value,
  409. //then that value is used as the module export value
  410. //instead of the object found via the 'exports' string.
  411. return this.Foo.noConflict();
  412. }
  413. }
  414. }
  415. });
  416. //Then, later in a separate file, call it 'MyModel.js', a module is
  417. //defined, specifying 'backbone' as a dependency. RequireJS will use
  418. //the shim config to properly load 'backbone' and give a local
  419. //reference to this module. The global Backbone will still exist on
  420. //the page too.
  421. define(['backbone'], function (Backbone) {
  422. return Backbone.Model.extend({});
  423. });
  424. </code></pre>
  425. <p>In RequireJS 2.0.*, the "exports" property in the shim config could have
  426. been a function instead of a string. In that case, it functioned
  427. the same as the "init" property as shown above. The "init" pattern is used in
  428. RequireJS 2.1.0+ so a string value for the exports can be used for
  429. <a href="#config-enforceDefine">enforceDefine</a>, but then allow
  430. functional work once the library is known to have loaded.</p>
  431. <p>For "modules" that are just jQuery or Backbone plugins that do not need to export
  432. any module value, the shim config can just be an array of dependencies:</p>
  433. <pre><code>requirejs.config({
  434. shim: {
  435. 'jquery.colorize': ['jquery'],
  436. 'jquery.scroll': ['jquery'],
  437. 'backbone.layoutmanager': ['backbone']
  438. }
  439. });
  440. </code></pre>
  441. <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:</p>
  442. <pre><code>requirejs.config({
  443. shim: {
  444. 'jquery.colorize': {
  445. deps: ['jquery'],
  446. exports: 'jQuery.fn.colorize'
  447. },
  448. 'jquery.scroll': {
  449. deps: ['jquery'],
  450. exports: 'jQuery.fn.scroll'
  451. },
  452. 'backbone.layoutmanager': {
  453. deps: ['backbone']
  454. exports: 'Backbone.LayoutManager'
  455. }
  456. }
  457. });
  458. </code></pre>
  459. <p><b>Important notes for "shim" config:</b></p>
  460. <ul>
  461. <li>The shim config only sets up code relationships. To load modules that
  462. are part of or use shim config, a normal require/define call is needed. Setting shim by
  463. itself does not trigger code to load.</li>
  464. <li>Only use other "shim" modules as dependencies for shimmed scripts, or
  465. AMD libraries that have no dependencies and call define() after they also
  466. create a global (like jQuery or lodash). Otherwise, if you use an AMD
  467. module as a dependency for a shim config module, after a build, that
  468. AMD module may not be evaluated until after the shimmed code in the build
  469. executes, and an error will occur. The ultimate fix is to upgrade all the
  470. shimmed code to have optional AMD define() calls.</li>
  471. </ul>
  472. <p><b>Important optimizer notes for "shim" config</b>:</p>
  473. <ul>
  474. <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>
  475. <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 for non-modular code, legacy code. define()'d modules are better.</li>
  476. <li>If you are using uglifyjs to minify the code, <strong>do not</strong> set the uglify
  477. option <code>toplevel</code> to true, or if using the command line
  478. <strong>do not</strong> pass <code>-mt</code>. That option mangles
  479. the global names that shim uses to find exports.</li>
  480. </ul>
  481. <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>
  482. <p>This sort of capability is really important for larger projects which may have
  483. two sets of modules that need to use two different versions of 'foo', but they
  484. still need to cooperate with each other.</p>
  485. <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>
  486. <p>map example:</p>
  487. <pre><code>requirejs.config({
  488. map: {
  489. 'some/newmodule': {
  490. 'foo': 'foo1.2'
  491. },
  492. 'some/oldmodule': {
  493. 'foo': 'foo1.0'
  494. }
  495. }
  496. });
  497. </code></pre>
  498. <p>If the modules are laid out on disk like this:</p>
  499. <ul>
  500. <li>foo1.0.js</li>
  501. <li>foo1.2.js</li>
  502. <li>some/
  503. <ul>
  504. <li>newmodule.js</li>
  505. <li>oldmodule.js</li>
  506. </ul>
  507. </li>
  508. </ul>
  509. <p>When 'some/newmodule' does `require('foo')` it will get the foo1.2.js file,
  510. and when 'some/oldmodule' does `require('foo')` it will get the foo1.0.js file.</p>
  511. <p>This feature only works well for scripts that are real AMD modules that call
  512. 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>
  513. <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>
  514. <pre><code>
  515. requirejs.config({
  516. map: {
  517. '*': {
  518. 'foo': 'foo1.2'
  519. },
  520. 'some/oldmodule': {
  521. 'foo': 'foo1.0'
  522. }
  523. }
  524. });
  525. </code></pre>
  526. <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>
  527. <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>
  528. <pre><code>requirejs.config({
  529. config: {
  530. 'bar': {
  531. size: 'large'
  532. },
  533. 'baz': {
  534. color: 'blue'
  535. }
  536. }
  537. });
  538. //bar.js, which uses simplified CJS wrapping:
  539. //http://requirejs.org/docs/whyamd.html#sugar
  540. define(function (require, exports, module) {
  541. //Will be the value 'large'
  542. var size = module.config().size;
  543. });
  544. //baz.js which uses a dependency array,
  545. //it asks for the special module ID, 'module':
  546. //https://github.com/jrburke/requirejs/wiki/Differences-between-the-simplified-CommonJS-wrapper-and-standard-AMD-define#wiki-magic
  547. define(['module'], function (module) {
  548. //Will be the value 'blue'
  549. var color = module.config().color;
  550. });
  551. </code></pre>
  552. <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>
  553. <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>
  554. <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>
  555. <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.</p>
  556. <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>
  557. <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>
  558. <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>
  559. <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>
  560. <pre><code>urlArgs: "bust=" + (new Date()).getTime()
  561. </code></pre>
  562. <p>During development it can be useful to use this, however <strong>be sure</strong> to remove it before deploying your code.</p>
  563. <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>
  564. </div>
  565. <div class="section">
  566. <h2>
  567. <a href="#advanced" name="advanced">Advanced Usage</a>
  568. <span class="sectionMark">&sect; 4</span>
  569. </h2>
  570. <h3><a href="#packages" name="packages">Loading Modules from Packages</a><span class="sectionMark">&sect; 4.1</span></h3>
  571. <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>
  572. <ul>
  573. <li>A package can be associated with a module name/prefix.</li>
  574. <li>The package config can specify the following properties for a specific package:
  575. <ul>
  576. <li><strong>name</strong>: The name of the package (used for the module name/prefix mapping)</li>
  577. <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>
  578. <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>
  579. </ul></li>
  580. </ul>
  581. <p><strong>IMPORTANT NOTES</strong></p>
  582. <ul>
  583. <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>
  584. <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>
  585. </ul>
  586. <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>
  587. <ul>
  588. <li>project-directory/
  589. <ul>
  590. <li>project.html</li>
  591. <li>scripts/
  592. <ul>
  593. <li>require.js</li>
  594. </ul></li>
  595. </ul></li>
  596. </ul>
  597. <p>Here is how the example directory layout looks with two packages, <strong>cart</strong> and <strong>store</strong>:</p>
  598. <ul>
  599. <li>project-directory/
  600. <ul>
  601. <li>project.html</li>
  602. <li>cart/
  603. <ul>
  604. <li>main.js</li>
  605. </ul></li>
  606. <li>store/
  607. <ul>
  608. <li>main.js</li>
  609. <li>util.js</li>
  610. </ul></li>
  611. <li>main.js</li>
  612. <li>require.js</li>
  613. </ul></li>
  614. </ul></li>
  615. </ul>
  616. <p><strong>project.html</strong> will have a script tag like this:</p>
  617. <pre><code>&lt;script data-main="scripts/main" src="scripts/require.js"&gt;&lt;/script&gt;
  618. </code></pre>
  619. <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>
  620. <pre><code>//main.js contents
  621. //Pass a config object to require
  622. require.config({
  623. "packages": ["cart", "store"]
  624. });
  625. require(["cart", "store", "store/util"],
  626. function (cart, store, util) {
  627. //use the modules as usual.
  628. });
  629. </code></pre>
  630. <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>
  631. <p>If the "store" package did not follow the "main.js" convention, and looked more like this:</p>
  632. <ul>
  633. <li>project-directory/
  634. <ul>
  635. <li>project.html</li>
  636. <li>scripts/
  637. <ul>
  638. <li>cart/
  639. <ul>
  640. <li>main.js</li>
  641. </ul></li>
  642. <li>store/
  643. <ul>
  644. <li>store.js</li>
  645. <li>util.js</li>
  646. </ul></li>
  647. <li>main.js</li>
  648. <li>package.json</li>
  649. <li>require.js</li>
  650. </ul></li>
  651. </ul></li>
  652. </ul>
  653. <p>Then the RequireJS configuration would look like so:</p>
  654. <pre><code>require.config({
  655. packages: [
  656. "cart",
  657. {
  658. name: "store",
  659. main: "store"
  660. }
  661. ]
  662. });
  663. </code></pre>
  664. <p>To avoid verbosity, it is strongly suggested to always use packages that use "main" convention in their structure.</p>
  665. <h3><a href="#multiversion" name="multiversion">Multiversion Support</a><span class="sectionMark">&sect; 4.2</span></h3>
  666. <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>
  667. <pre><code>&lt;script src="../require.js"&gt;&lt;/script&gt;
  668. &lt;script&gt;
  669. var reqOne = require.config({
  670. context: "version1",
  671. baseUrl: "version1"
  672. });
  673. reqOne(["require", "alpha", "beta",],
  674. function(require, alpha, beta) {
  675. log("alpha version is: " + alpha.version); //prints 1
  676. log("beta version is: " + beta.version); //prints 1
  677. setTimeout(function() {
  678. require(["omega"],
  679. function(omega) {
  680. log("version1 omega loaded with version: " +
  681. omega.version); //prints 1
  682. }
  683. );
  684. }, 100);
  685. });
  686. var reqTwo = require.config({
  687. context: "version2",
  688. baseUrl: "version2"
  689. });
  690. reqTwo(["require", "alpha", "beta"],
  691. function(require, alpha, beta) {
  692. log("alpha version is: " + alpha.version); //prints 2
  693. log("beta version is: " + beta.version); //prints 2
  694. setTimeout(function() {
  695. require(["omega"],
  696. function(omega) {
  697. log("version2 omega loaded with version: " +
  698. omega.version); //prints 2
  699. }
  700. );
  701. }, 100);
  702. });
  703. &lt;/script&gt;
  704. </code></pre>
  705. <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>
  706. <h3><a href="#afterload" name="afterload">Loading Code After Page Load</a><span class="sectionMark">&sect; 4.3</span></h3>
  707. <p>The example above in the <strong>Multiversion Support</strong> section shows how code can later be loaded by nested require() calls. </p>
  708. <h3><a href="#webworker" name="webworker">Web Worker Support</a><span class="sectionMark">&sect; 4.4</span></h3>
  709. <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>
  710. <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>
  711. <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>
  712. <h3><a href="#rhino" name="rhino">Rhino Support</a><span class="sectionMark">&sect; 4.5</span></h3>
  713. <p>RequireJS can be used in Rhino via the <a href="download.html#rjs">r.js adapter</a>.
  714. See <a href="https://github.com/jrburke/r.js/blob/master/README.md">the r.js README</a> for more information.</p>
  715. <h3><a href="#errors" name="errors">Handling Errors</a><span class="sectionMark">&sect; 4.6</span></h3>
  716. <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-

Large files files are truncated, but you can click here to view the full file