RequireJS 插件
RequireJS 插件
RequireJS包含了一些插件,这些插件允许加载各种类型的资源。以下是RequireJS中常用插件列表:
text
domReady
i18n
CSS加载
text
text插件用于异步加载基于文本的资源(如html文件,txt文本等),主要用于在JavaScript文件中插入HTML内容。使用文本时可以加载它!任何需要或定义模块调用中的前缀,并将文件扩展名传递给插件。与正常模块加载相比,文本插件使用XHR加载模块,不会将代码作为脚本标记添加到标头中。
text可以作为依赖项包含在代码中,如 −
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中。
define({ "root": { "india": "india", "australia": "australia", "england": "england" } });
您可以使用fr-fr locale设置将特定转换添加到文件中,上述代码将更改为:
define({ "root": { "title": "title", "header": "header", "description": "description" }, "es-es": true });
接下来,在mydirectory/nls/es-es/national.js中指定文件,其中包含以下内容
define({ "root": { "title": "título", "header": "cabecera", "description": "descripción" }, "es-es": true });
您可以通过在主.js文件中的模块配置的帮助下将其传递给插件来设置区域设置,如下所示
requirejs.config({ config: { //set the config for the i18n plugin i18n: { locale: 'es-es' } } });
使用RequireJS加载CSS
您可以使用一些插件加载CSS文件,方法是仅附加到标头链接以加载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); }