require.js讀書筆記 2.usage

來源:互聯網
上載者:User

標籤:style   http   color   io   os   ar   使用   java   for   

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 載入javascript檔案夾§ 1.1

requireJs用一種新的script載入方法,這種方法和傳統<script>標籤是完全不同的。它可以運行地更快,並且進行更好地最佳化,它的主要目的就是為了支援(encourage)模組化(modular)代碼的載入。作為其中的一部分,它支援利用模組ID來載入script,而不是script標籤裡的url屬性。

requireJs載入的所有代碼地址都是相對於baseUrl的。頁面頂層script標籤有一個特殊的屬性data-main,require.js用它來啟動指令碼載入頁面,而baseUrl通常設定成這個標籤所在的檔案夾裡。data-main attribute是一個特殊的屬性,require.js會用這個屬性進行載入。下面這個例子會展示了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>

或者,baseUrl可以通過RequireJS config手動(manually)地設定。如果沒有明確的(explicit)config設定,或者沒有使用data-main屬性,那麼預設的baseUrl就是包含requireJs的HTML頁面所在的目錄。

requireJs預設所有依賴(dependence)資源都死scripts,所以寫模組ID時不需要.js的尾碼。requireJs翻譯模組ID的路徑時會自動加上.js尾綴的。運用paths config標籤,你可以設定一組scripts指令碼的位置。相對於<script>標籤,這些能讓你用更少的字元來載入script。

有時候你想直接飲用一個script,而不是依照(conform)“baseUrl+paths"規則來找它。如果一個模組ID由以下之一的規則,這個ID就不會通過”baseUrl+paths"配置來載入script,而是像普通的script url屬性來載入。

  • 以.js結束
  • 以“/”開始
  • url協議(protocol),像 "http:" or "https:".

通常地說,最好通過baseUrl和paths來設定模組ID的路徑。這樣所,你可以很方便地重新命名和重定位指令碼(configuring the paths to different locations)。

相似的,為了避免配置淩亂,最好避免多級嵌套(deep folder hierarchies)的方式來載入代碼。要麼將所有的scripts放在baseUrl的目錄中,不然將你的代碼分置為目錄(library)/第三方目錄庫(vendor)的結構,可以像以下所示:

  • 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.});

在這個例子中,第三方庫(vendor其實是供應商的意思)如jQuery,並沒有將它的版本號碼顯示在檔案名稱中。如果你想跟蹤版本號碼,建議新開一個單獨的檔案來記錄,或者你可以用一些工具,像volo,可以將package.json打上版本資訊,但檔案名稱還是jQuery.js。這有助於你的配置最小化,避免為每個版本的庫設定paths路徑。例如,將"jquery"配置成(configure)“jquery-1,7,2"

理想狀態下(ideally),每個載入的指令碼都是通過define()來定義的一個模組。然而,有些"瀏覽器全域變數注入"型傳統/遺留(legacy)瀏覽器可能不能用define()來定義它們的依賴關係。為此(for those),你可以用shim config來解析它們的依賴關係。

如果你不想解析它們的依賴關係,你可能會得到一些載入錯誤,基於速度的原因(for speed),requireJs會非同步( asynchronously)、無序(out of order)地載入指令碼。

 

data-main Entry Point§ 1.2

data-main屬性是一個特殊屬性,require.js在載入指令碼的時候會檢查(check)它:

<!--當require.js載入的時候,它會忽視script/main.js的其他script標籤屬性--><script data-main="scripts/main" src="scripts/require.js"></script>

你可以在data-main中設定配置選項,然後載入你的第一個應用模組(application module)。注意:require.js的標籤載入的模組是非同步async attribute。這意味著,如果你在這個頁面載入了其他scripts,則不能保證通過require.js載入的頁面可以先於這些指令碼載入完畢。

舉個例子,以下的構造不能保證foo模組的require.config的路徑設定會先於require()foo模組執行:

<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

require([‘foo‘], function(foo) { });

如果你想在HTML頁面中調用require(),最好不要用data-main。data-main只用在頁面只需要一個入口的時候。如果頁面想在行內調用require(),最好如下所示書寫代碼

<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 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 Module Pattern, with the benefit of not needing globals to refer to other modules.

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 load multiple versions of a module in a page.

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

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

Simple Name/Value Pairs§ 1.3.1

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():

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

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():

//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 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:

//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 are structured like this:

  • my/cart.js
  • my/inventory.js
  • my/shirt.js

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

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.

Modules that define globals are explicitly discouraged, so that multiple versions of a module can exist in a page at a time (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 defining modules in this way, "my/shirt" does not exist as a global object.

Define a Module as a Function

require.js讀書筆記 2.usage

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.