1. 程式人生 > >RequireJS 是一個JavaScript模組載入器

RequireJS 是一個JavaScript模組載入器

RequireJS 是一個JavaScript模組載入器。它非常適合在瀏覽器中使用, 它非常適合在瀏覽器中使用,但它也可以用在其他指令碼環境, 就像 Rhino and Node. 使用RequireJS載入模組化指令碼將提高程式碼的載入速度和質量。

IE 6+ .......... 相容 ✔
Firefox 2+ ..... 相容 ✔
Safari 3.2+ .... 相容 ✔
Chrome 3+ ...... 相容 ✔
Opera 10+ ...... 相容 ✔

 

獲取 REQUIREJS§ 1

去 下載 頁面下載檔案。

新增 REQUIREJS§ 2

注意: 關於 jQuery 整合的意見, 請看 jQuery 整合頁面

假定你的專案中 JavaScript 都放在一個 "scripts" 目錄。 例如, 你的專案中有一個 project.html 頁面和一些 scripts, 目錄佈局如下:

  • 專案目錄/
    • project.html
    • scripts/
      • main.js
      • helper/
        • util.js

新增 require.js 到 scripts 目錄, 如下:

  • 專案目錄/
    • project.html
    • scripts/
      • main.js
      • require.js
      • helper/
        • util.js

為了充分利用的優化工具,建議您將所有的scripts放到的HTML外面, 然後只引用 require.js 來請求載入你其它的scripts:

<!DOCTYPE html>
<html>
    <head>
        <title>My Sample Project</title>
        <!-- data-main attribute tells require.js to load
             scripts/main.js after require.js loads. -->
        <script data-main="scripts/main" src="scripts/require.js"></script>
    </head>
    <body>
        <h1>My Sample Project</h1>
    </body>
</html>

在 main.js, 你可以使用 require() 來載入所有你需要執行的scripts. 這可以確保你所有的scripts都是在這裡載入的, 你可以 指定 data-main script 使用非同步載入.

require(["helper/util"], function(util) {
    //This function is called when scripts/helper/util.js is loaded.
    //If util.js calls define(), then this function is not fired until
    //util's dependencies have loaded, and the util argument will hold
    //the module value for "helper/util".
});

載入 helper/util.js 指令碼. 想要充分利用 RequireJS, 請看 API 文件 去了解更多相關定義和模組的使用

優化§ 3

如果你最終決定在你在程式碼中使用, 可以使用 優化 結合 JavaScript 檔案來減少載入時間. 在上面的例子中, 你可以結合 main.js 和 helper/util.js 加到一個檔案中.