- RequireJS 教程
- RequireJS - 首頁
- RequireJS - 概述
- RequireJS - 環境搭建
- RequireJS - 配置
- RequireJS - AMD 模組
- RequireJS - 定義函式
- RequireJS - 最佳化器
- RequireJS - jQuery
- RequireJS - NodeJS
- RequireJS - Dojo
- RequireJS - CommonJS
- RequireJS - 外掛
- RequireJS 有用資源
- RequireJS - 快速指南
- RequireJS - 有用資源
- RequireJS - 討論
RequireJS - 外掛
RequireJS包含少量外掛,允許載入各種型別的資源作為依賴項。以下是RequireJS中可用外掛的列表:
- text
- domReady
- i18n
- CSS 載入
text
text 外掛用於非同步載入基於文字的資源,主要用於在 JavaScript 檔案中插入 HTML 內容。當在任何 require 或 define 模組呼叫中使用 text! 字首並將副檔名傳遞給外掛時,可以載入它。與正常的模組載入相比,text 外掛使用 XHR 載入模組,不會將程式碼作為script標籤新增到 header 中。
文字檔案資源可以作為程式碼中的依賴項包含,如下所示:
require(["mymodule", "text!mymodule.html", "text!mymodule.css"],
function(mymodule, html, css) {
//the html and css variables will be the text
//of the mymodule.html file and mymodule.css files respectively
}
);
domReady
RequireJS 可用於在 DOM 準備就緒之前載入指令碼,開發人員只有在指令碼完全載入後才能與 DOM 互動。有時指令碼可能在 DOM 準備就緒之前載入。因此,為了克服這個問題,RequireJS 提供了一種現代方法,稱為DOMContentLoaded 事件,該事件在 DOM 準備就緒後呼叫 domReady 函式。
require(['domReady'], function(domReady) {
domReady(function() {
//the domReady function is called when DOM is ready
//which is safe to manipulate DOM nodes in this function
});
});
i18n
它可以與多個語言環境一起使用,這些語言環境提供i18n包支援,當模組或依賴項指定“i18n!”字首時,這些包將自動載入。要使用此功能,請下載它並將其放在主 JavaScript 檔案所在的同一目錄中。將此外掛放在名為“nls”的目錄中以找到您的本地化檔案。
例如,假設我們有一個名為country.js的 js 檔案,其內容如下,並將其放在mydirectory/nls/country.js目錄中:
define({
"root": {
"india": "india",
"australia": "australia",
"england": "england"
}
});
您可以透過使用fr-fr語言環境為檔案新增特定的翻譯,上面的程式碼將更改為:
define({
"root": {
"title": "title",
"header": "header",
"description": "description"
},
"es-es": true
});
接下來,在mydirectory/nls/es-es/country.js中指定具有以下內容的檔案:
define({
"root": {
"title": "título",
"header": "cabecera",
"description": "descripción"
},
"es-es": true
});
您可以透過在main.js檔案中使用模組配置將語言環境傳遞給外掛來設定語言環境,如下所示:
requirejs.config({
config: {
//set the config for the i18n plugin
i18n: {
locale: 'es-es'
}
}
});
使用RequireJS載入CSS
您可以使用一些外掛透過簡單地將連結附加到 header 來載入 CSS 檔案。
可以使用您自己的函式載入 CSS,如下所示:
function myCss(url) {
var mylink = document.createElement("mylink");
mylink.type = "text/css";
mylink.rel = "stylesheet";
mylink.href = url;
document.getElementsByTagName("head")[0].appendChild(mylink);
}