取得 RequireJS § 1
前往 下載 頁面並取得檔案。
加入 RequireJS § 2
注意:有關 jQuery 的特定建議,請參閱 jQuery 整合頁面此設定假設您將所有 JavaScript 檔案都保存在專案中的「scripts」目錄中。例如,如果您有一個專案包含一個 project.html 頁面,以及一些腳本,目錄配置可能會如下所示
- project-directory/
- project.html
- scripts/
- main.js
- helper/
- util.js
將 require.js 加入 scripts 目錄,如下所示
- project-directory/
- project.html
- scripts/
- main.js
- require.js
- helper/
- util.js
為充分利用最佳化工具,建議您將所有內嵌腳本從 HTML 中移除,並僅使用 requirejs 呼叫來參照 require.js,如下載入您的腳本
<!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>
如果您不希望 require.js 腳本的載入會阻擋呈現,您也可以將腳本標籤放在 <body> 區段的結尾。對於支援的瀏覽器,您也可以將 async 屬性 加入腳本標籤。
在 main.js 內部,您可以使用 requirejs() 載入您需要執行的任何其他腳本。這可確保單一進入點,因為 您指定的 data-main 腳本會非同步載入。
requirejs(["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 文件,以深入了解如何定義和使用模組。