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