Require.js Reading Note 2.usage

Source: Internet
Author: User
Tags script tag

Requirejs APIThis is the Requirejs 2.0 API. If you want 1.0:link to 1.0.
  • Usage§§1-1.3
    • Load JavaScript Files §1.1
    • Data-main Entry Point§1.2
    • Define a Module§1.3
      • Simple Name/value Pairs§1.3.1
      • Definition Functions§1.3.2
      • Definition Functions with Dependencies§1.3.3
      • Define a Module as a Function§1.3.4
      • Define a Module with simplified CommonJS Wrapper§1.3.5
      • Define a Module with a name§1.3.6
      • Other Module Notes§1.3.7
      • Circular Dependencies§1.3.8
      • Specify a JSONP Service Dependency§1.3.9
      • Undefining a Module§1.3.10
  • Mechanics§§2
  • Configuration Options§§3
  • Advanced Usage§§4-4.6
      • Loading Modules from Packages§4.1
      • Multiversion support§4.2
      • Loading Code after Page Load§4.3
      • Web Worker support§4.4
      • Rhino support§4.5
      • Handling Errors§4.6
  • Loader Plugins§§5-5.4
      • Specify a Text File Dependency§5.1
      • Page Load Event support/dom ready§5.2
      • Define an i18n Bundle§5.3
USAGE§1Load JavaScript files loading JavaScript folder§1.1

Requirejs with a new script loading method, this method is completely different from the traditional <script> tag. It can be run faster and better optimized, and its primary purpose is to support the loading of (encourage) modular (modular) code. As part of this, it supports loading script with the module ID instead of the URL attribute in the script tag.

All code addresses loaded by Requirejs are relative to BaseURL. The script tag at the top of the page has a special property data-main,require.js use it to launch scripts to load the page, and BaseURL is usually set to the folder where the tag is located. Data-main attribute is a special property that Require.js will load with this property. The following example shows the settings of the BaseURL:

<!--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>

Alternatively, the BaseURL can be set manually (manually) by Requirejs Config. If there is no explicit (explicit) config setting, or if the Data-main property is not used, the default baseurl is the directory containing the Requirejs HTML page.

Requirejs Default all dependent (dependence) resources are dead scripts, so it is not necessary to write the module ID. js suffix. Requirejs the path of the translation module ID is automatically added with the. js suffix. Using the Paths config tag, you can set the location of a set of scripts scripts. These allow you to load script with fewer characters relative to the <script> tag.

Sometimes you want to drink a script directly, rather than follow (conform) "baseurl+paths" rules to find it. If a module ID consists of one of the following rules, this ID will not be loaded with the "baseurl+paths" configuration, but rather like the normal script URL property.

    • End With. js
    • Start with "/"
    • The URL Protocol (protocol), like "http:" or "https:".

Generally speaking, it is best to set the path of the module ID through BaseURL and paths. In this way, you can easily rename and reposition the script (configuring the Paths to different locations).

Similarly, to avoid configuration clutter, it is best to avoid multiple levels of nesting (deep folder hierarchies) to load code. Either put all the scripts in the BaseURL directory, or you can split your code into a directory (library)/third-party directory library (vendor) structure, as shown here:

    • www/
      • Index.html
      • js/
        • app/
          • Sub.js
        • lib/
          • Jquery.js
          • Canvas.js
        • App.js

In index.html:

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

And in App.js:

requirejs.config({    //设置默认模块ID的路径 js/lib    baseUrl: ‘js/lib‘,    //另外,如果模块ID以app开始,    //它会从js/app目录加载。paths设置时相对于baseUrl的,绝不会包括“.js”的,但是paths设置可以是相对directory的    paths: {        app: ‘../app‘    }});
开始main app的逻辑。
requirejs([‘jquery‘, ‘canvas‘, ‘app/sub‘],function ($, canvas, sub) { //jQuery, canvas and the app/sub module are all //loaded and can be used here now.});

In this example, the third-party library (vendor is actually the vendor's meaning), such as jquery, does not display its version number in the file name. If you want to track the version number, it is recommended to open a separate file to record, or you can use some tools, like Volo, can be Package.json version information, but the file name or Jquery.js. This helps you minimize the configuration and avoids setting the paths path for each version of the library. For example, "jquery" is configured as (configure) "jquery-1,7,2"

Ideally (ideally), each loaded script is a module defined by define (). However, some "browser global variable Injection" type legacy/Legacy (Legacy) browsers may not be able to define their dependencies with define (). For this purpose (for those), you can use Shim Config to parse their dependencies.

If you do not want to parse their dependencies, you may get some load errors, based on the speed of the reason (for Requirejs), and the script will be loaded asynchronously (asynchronously), out of order (out of).

Data-main Entry Point§1.2

The Data-main property is a special property that Require.js checks (check) when the script is loaded:

<!--当require.js加载的时候,它会忽视script/main.js的其他script标签属性--><script data-main="scripts/main" src="scripts/require.js"></script>

You can set the configuration options in Data-main and then load your first application module (Application module). Note: The require.js tag-loaded module is async async attribute. This means that if you load other scripts on this page, there is no guarantee that pages loaded through Require.js can be loaded before those scripts.

For example, the following constructs do not guarantee that the Require.config path setting of the Foo module will precede the Require () Foo module:

<script data-main="scripts/main" src="scripts/require.js"></script><script src="scripts/other.js"></script>
// contents of main.js:require.config({    paths: {        foo: ‘libs/foo-1.1.3‘    }});
// contents of other.js://这段代码可能会在main.js 的require.config()之前执行。如果这放生了,require.js会加载‘scripts/foo.js‘额不是‘scripts/libs/foo-1.1.3.js


If you want to call require () in an HTML page, it's best not to use Data-main. Data-main is only used when the page needs only one entry. If the page wants to call require () within a row, it is best to write the code as shown below

<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>
Define a Module§1.3

A module is different from a traditional script file in that it defines a well-scoped object that avoids polluting the Glo Bal namespace. It can explicitly list its dependencies and get a handle in 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 is an extension of the Module Pattern, with the benefit of not needing globals to refer to other mods Ules.

The REQUIREJS syntax for modules allows them to being loaded as fast as possible, even out of order, but evaluated in the COR Rect dependency order, and since global variables is not created, it makes it possible to load multiple versions of a mod Ule in a page.

(If you is familiar with or is using CommonJS modules, then please also see CommonJS Notes for information on how the Re QUIREJS module format maps to CommonJS modules).

There should only is one module definition per file on disk. The modules can be grouped to optimized bundles by the optimization tool.

Simple Name/value Pairs§1.3.1

If The module does not has any dependencies, and it's just a collection of name/value pairs, then just pass an object Li Teral to define ():

//Inside file my/shirt.js:define({    color: "black",    size: "unisize"});
Definition Functions§1.3.2

If The module does not has dependencies, but needs to use a function to do some setup work, then define itself, pass a FU Nction to define ():

//my/shirt.js now does setup work//before returning its module definition.define(function () {    //Do setup work here    return {        color: "black",        size: "unisize"    }});
Definition Functions with Dependencies§1.3.3

If The module has dependencies, the first argument should is an array of dependency names, and the second argument should Be a definition function. The function would be called to define the module once all dependencies has loaded. The function should return an object that defines the module. The dependencies is passed to the definition function as function arguments, and listed in the same order as the The dependency array:

//my/shirt.js now has some dependencies, a cart and inventory//module in the same directory as shirt.jsdefine(["./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);            }        }    });

In this example, a My/shirt module is created. It depends on My/cart and my/inventory. On disk, the files is structured like this:

    • My/cart.js
    • My/inventory.js
    • My/shirt.js

The function call above specifies the arguments, "cart" and "inventory". These is the modules represented by the "./cart" and "./inventory" module names.

The function is not called until the My/cart and My/inventory modules has been loaded, and the function receives the MODU Les as the "cart" and "inventory" arguments.

Modules that define globals is explicitly discouraged, so the multiple versions of a module can exist in a page at a Tim E (see Advanced Usage). Also, the order of the function arguments should match the order of the dependencies.

The return object from the function call defines the "My/shirt" module. By the defining modules in the This-"my/shirt" does not exist as a global object.

Define a Module as a Function

Require.js Reading Note 2.usage

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.