diff --git a/docs/api.html b/docs/api.html index 7e3027b97..15ff66091 100644 --- a/docs/api.html +++ b/docs/api.html @@ -33,9 +33,8 @@
If you just want to load some JavaScript files, use the require()
API. If there is already a require()
in the page, you can use requirejs()
to access the RequireJS API for loading scripts.
RequireJS takes a different approach to script loading that traditional <script> 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 module IDs instead of URLs for script tags.
-Here is a simple example of calling require()
:
RequireJS loads all code relative to a baseUrl. 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 scripts:
-<script src="scripts/require.js"></script>
-<script>
- require(["some/module", "a.js", "b.js"], function(someModule) {
- //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>
+<--This sets the baseUrl to the "scripts" directory-->
+<script data-main="scripts/main.js" src="scripts/require.js"></script>
-The dependencies above, ["some/module", "a.js", "b.js"], will be loaded via script tags that have the following src values:
-
-
-- some/module.js
-- a.js (in the same directory as the HTML page that has the above HTML snippet)
-- b.js (in the same directory as the HTML page that has the above HTML snippet)
-
+Or, baseUrl can be set manually via the RequireJS config. 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.
-RequireJS normally uses the baseUrl and paths configuration to convert names like "some/module" into a file path.
+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 paths config, 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.
-However, if the dependency name has one of the following properties, it is treated as a regular file path, like something that was passed to a <script src=""> tag:
+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:
- Ends in ".js".
@@ -84,30 +71,63 @@
- Contains an URL protocol, like "http:" or "https:".
-See the Configuration Options section for information on changing the lookup paths used for dependencies.
+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.
-While you can use require() inside a script tag in an HTML file, it is strongly encouraged to place the work in a file that is loaded by RequireJS. This allows for easier optimization via the optimization tool, and there is a shorthand that can be used in the HTML for this pattern. The above example would be structured like this:
+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:
-<script data-main="scripts/main" src="scripts/require.js"></script>
-
+
+ - www/
+
+ - index.html
+ - js/
+
+ - app/
+
+ - sub.js
+
+
+ - lib/
+
+ - jquery.js
+ - canvas.js
+
+ - app.js
+
+
+
+
+in index.html:
-The path rules used for data-main changed in RequireJS 0.23. Before that version, data-main="main" for the above example.
+<script data-main="js/app.js" src="js/require.js"></script>
-The data-main attribute tells RequireJS to take the value of the data-main attribute and treat it like a require([]) call. So, in this case, it would load scripts/main.js, and that file should have the top-level require call:
+and in main.js:
-//Inside scripts/main.js
-require(["some/module", "a.js", "b.js"], function(someModule) {
- //...
+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'
+ }
});
-
-The directory that contains the data-main script also then becomes the root URL value (or baseUrl in the RequireJS terms) to find other scripts that use the module naming scheme, the scheme that does not end a ".js" extension. In this example "some/module" is using the module naming scheme, where "a.js" and "b.js" are not.
+// 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.
+});
+
-Since data-main was used, and main.js is in the scripts directory, the baseUrl for RequireJS becomes the scripts directory. The "some/module" script would map to a path relative to the scripts directory. So it would be found at scripts/some/module.js.
+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 volo, 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".
-Note how this is different from the first example where "some/module" was found at some/module.js. If data-main is not used and an explicit baseUrl value is not passed in the RequireJS configuration, then then the default baseUrl is the directory containing the HTML page that loads RequireJS.
+Ideally the scripts you load will be modules that are defined by calling define(). 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 shim config. To properly express their dependencies.
-Script names that are just regular paths ending in ".js", start with a "/" or have a protocol in them are always mapped relative to the HTML page instead of relative to baseUrl, just like HTML <script> src="" values. You can use the "module naming scheme" even if the script does not define a module, it is just means the path will be relative to baseUrl in that case.
+If you do not express the dependencies, you will likely get loading errors since RequireJS loads scripts asynchronously and out of order for speed.
Define a Module
@@ -414,8 +434,7 @@
paths: {
"some": "some/v1.0"
},
- waitSeconds: 15,
- locale: "fr-fr"
+ waitSeconds: 15
});
require( ["some/module", "my/module", "a.js", "b.js"],
function(someModule, myModule) {
@@ -451,43 +470,97 @@
Supported configuration options:
-baseUrl: 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 not used when loading plain .js files, 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.
+baseUrl: 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 not used when loading plain .js files, 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.
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 data-main attribute is used, that path will become the baseUrl.
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.
-paths: 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:"). In those cases, the path is determined relative to baseUrl. Using the above sample config, "some/module"'s script tag will be src="/another/path/some/v1.0/module.js". The path that is used for a module name should not include the .js 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.
+paths: 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:"). In those cases, the path is determined relative to baseUrl. Using the above sample config, "some/module"'s script tag will be src="/another/path/some/v1.0/module.js". The path that is used for a module name should not include the .js 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.
+
+shim: 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. Example:
+
+
+requirejs.config({
+ 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'
+ },
+ 'foo': {
+ deps: ['bar'],
+ //A function can be used to generate the exported value.
+ //"this" for the function will be the global object.
+ //The dependencies will be passed in as function arguments.
+ exports: function (bar) {
+ //Using a function allows you to call noConflict for libraries
+ //that support it. However, be aware that plugins for those
+ //libraries may still want a global.
+ return this.Foo.noConflict();
+ }
+ }
+ }
+});
+
+
+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:
+
+requirejs.config({
+ shim: {
+ 'jquery.colorize': ['jquery'],
+ 'jquery.scroll': ['jquery'],
+ 'backbone.layoutmanager': ['backbone']
+ }
+});
+
-packages: configures loading modules from CommonJS packages. See the packages topic for more information.
+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:
+
+requirejs.config({
+ shim: {
+ 'jquery.colorize': {
+ deps: ['jquery'],
+ exports: 'jQuery.fn.colorize'
+ },
+ 'jquery.scroll': {
+ deps: ['jquery'],
+ exports: 'jQuery.fn.colorize'
+ },
+ 'backbone.layoutmanager': {
+ deps: ['backbone']
+ exports: 'Backbone.LayoutManager'
+ }
+ }
+});
+
-waitSeconds: The number of seconds to wait before giving up on loading a script. The default is 7 seconds.
+packages: configures loading modules from CommonJS packages. See the packages topic for more information.
-locale: The locale to use for loading i18n bundles. By default navigator.language or navigator.userLanguage will be used. The proper syntax for specifying a locale is using lowercase and separating values by dashes, for instance: "fr-fr-paris" or "en-us".
+waitSeconds: The number of seconds to wait before giving up on loading a script. The default is 7 seconds.
-context: 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 Multiversion Support section.
+context: 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 Multiversion Support section.
-deps: 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.
+deps: 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.
-callback: A function to pass to require that should be require after deps 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 deps array has been loaded.
+callback: A function to pass to require that should be require after deps 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 deps array has been loaded.
-priority: An array of module/file names to load immediately, before tracing down any other dependencies. This allows you to set up a small set of files that are downloaded in parallel that contain most of the modules and their dependencies already built in. More information is in the Optimization FAQ, Priority Downloads.Note: resources loaded by loader plugins (like 'text!template.html') cannot be specified in the priority array: the priority mechanism only works with regular JavaScript resources.
+priority: An array of module/file names to load immediately, before tracing down any other dependencies. This allows you to set up a small set of files that are downloaded in parallel that contain most of the modules and their dependencies already built in. More information is in the Optimization FAQ, Priority Downloads.Note: resources loaded by loader plugins (like 'text!template.html') cannot be specified in the priority array: the priority mechanism only works with regular JavaScript resources.
-xhtml: If set to true, document.createElementNS() will be used to create script elements.
+xhtml: If set to true, document.createElementNS() will be used to create script elements.
-urlArgs: 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:
+urlArgs: 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:
urlArgs: "bust=" + (new Date()).getTime()
During development it can be useful to use this, however be sure to remove it before deploying your code.
-jQuery: (RequireJS 0.25.0+) specify an exact version match for the version of jQuery that should be allowed to register as the 'jquery' dependency. This is useful in environments where multiple jQuery files could be loaded but you want
-to be sure to get the right version of jQuery for your loading context. Normally you do not need to set this if you are only loading one version of jQuery in a page. However, if you use third party libraries that may also load jQuery, it is best to set this option.
-
-scriptType: (RequireJS 1.0.4+) 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".
-
-catchError: (RequireJS 0.26.0+) Normally, errors evaluating define() factory functions are not caught, to allow easy debugging during development. However, for some scenarios and production deployments, it is useful to have the errors caught. By specifying catchError.define = true, the errors will be caught and passed to requirejs.onError(). Normally requirejs.onError() throws the error, but you can override the definition of requirejs.onError() to do something different.
+scriptType: 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".
@@ -709,8 +782,14 @@ Handling Errors
-If you want errors that occur as part of calling the define() factory function to create a module export value, you can set catchError to true, and any errors from running the factory function will be passed to -requirejs.onError().
+If you want errors that occur as part of calling the define() factory function to create a module export value, you can pass an errback to the require call that will load it:
+ +require(['moduleThatMayError'], function (mod) {
+ //loaded OK
+}, function (err) {
+ //error loading or evaluating it.
+});
+
@@ -757,27 +836,7 @@ Normally RequireJS loads and evaluates scripts in an undetermined order. However, there are some traditional scripts that depend on being loaded in a specific order. For those cases you can use the order plugin. Download the plugin and put it in the same directory as your app's main JS file. Example usage:
- -require(["order!one.js", "order!two.js", "order!three.js"], function () {
- //This callback is called after the three scripts finish loading.
-});
-
-
-Scripts loaded by the order plugin will be fetched asynchronously, but evaluated in the order they are passed to require, so it should still perform better than using script tags in the head of an HTML document.
- -The order plugin is best used with traditional scripts. It is not needed for scripts that use define() to define modules. It is possible to mix and match "order!" dependencies with regular dependencies, but only the "order!" ones will be evaluated in relative order to each other.
- -Notes:
-It is possible when using RequireJS to load scripts quickly enough that they complete before the DOM is ready. Any work that tries to interact with the DOM should wait for the DOM to be ready. For modern browsers, this is done by waiting for the DOMContentLoaded event.
@@ -809,23 +868,7 @@DOM Ready with implicit dependencies: If you are working on a project that does not use require() and define() to explicitly indicate dependencies in all scripts, you many notice some errors when waiting for the DOM to be ready then executing code that depends on those implicit dependencies.
- -The best fix is to wrap all scripts in explicit define() calls that specify all the direct dependencies. However, if that is not an option, you can call a special method on the domReady plugin to wait for all scripts to load and the DOM to be ready:
- -require(['domReady'], function (domReady) {
- domReady.withResources(function () {
- //This function is called once the DOM is ready,
- //and all modules/plugin resources that RequireJS is loading
- //finish loading.
- }):
-});
-
-
-You should avoid using this function, and instead be very explicit about the dependencies in each file. -However, as an intermediate patch to get a project working with RequireJS, it can be useful.
- -Once your web app gets to a certain size and popularity, localizing the strings in the interface and providing other locale-specific information becomes more useful. However, it can be cumbersome to work out a scheme that scales well for supporting multiple locales.
@@ -888,7 +931,18 @@RequireJS will use the browser's navigator.language or navigator.userLanguage property to determine what locale values to use for my/nls/colors, so your app does not have to change. If you prefer to set the locale, you can use the module config to pass the locale to the plugin:
+ +requirejs.config({
+ config: {
+ //Set the config for the i18n
+ //module ID
+ i18n: {
+ locale: 'fr-fr'
+ }
+ }
+});
+
Note that RequireJS will always use a lowercase version of the locale, to avoid case issues, so all of the directories and files on disk for i18n bundles should use lowercase locales.
diff --git a/docs/download.html b/docs/download.html index 0c2ade8be..f32eb15fd 100644 --- a/docs/download.html +++ b/docs/download.html @@ -11,9 +11,8 @@A zip file containing a sample project that uses jQuery and RequireJS.
@@ -86,17 +85,6 @@Load script in the order specified in the dependency array. Useful for existing scripts that have implied dependencies instead of calling define() to create modular code.
-Same as RequireJS 0.27.1 release, with some document updates and a -small fix to the optimizer's regular expression for converting CommonJS modules to AMD.
- -RequireJS 1.0 release candidate. Small bugfixes for 0.27.0:
- -RequireJS 1.0 release candidate.
- -The awesome part: the optimizer is now just one JS file! It also doubles as a bootstrap script that supports the full capability of AMD modules and loader plugins in Node and in Rhino.
- -To use the optimizer, pass the "-o" option to r.js:
- -node r.js -o app.build.js- -
To run your AMD-based project via the adapter (assuming server.js is your top-level AMD module):
- -node r.js server.js- -
There is more information about running AMD modules in Node. The optimizer docs have been updated to the new optimizer syntax, and the r.js script has its own project now, to allow releases that are decoupled from require.js.
- -Other highlights:
- -Some changes in the name of compatibility with other AMD module loaders and Node:
- - -A small change to the context-specific require() passed to a loader plugin's load() call: require.isDefined() is now require.defined() and there is require. specified().
- -Some options:
Note that before 0.24.0, the text!, i18n! and order! plugins were "special" in that you only need to use a name like "text" to refer to it, but the actual module name was "require/text". This was done to support old code that was authored before the Plugin API was fully fleshed out. That magic module name transformation is no longer done in 0.24.0 and greater.
-Inside of main.js, you can use require() to load any other scripts you need to run:
require(["helper/util"], function(util) {
@@ -96,7 +94,9 @@
});
-That is it! Check out the API docs to learn more about require() and define().
+That will load the helper/util.js script. To get full advantage of RequireJS, +see the API docs to learn more about defining and using +modules.