jquery.artDialog估计没有支持AMD规范,所以当使用requireJS和AMD的模块化方法时,一开时没有碰到问题。后来在慢速网络环境下,发现jquery还没有完全加载完成,artDialog已经加载完并报错,导致总是要重新刷一次页面。
requireJS提供的解决方案叫做shim, 参考文档:http://requirejs.org/docs/api.html#config-shim
反复实验了多次,搞明白了怎么做:
1.每个html页面里面都会加载一个js文件,在这个js文件里面调用require.config,所有的配置都写在里面,包括shim
比如我的页面叫login.html,里面加载了loginModule.js文件:
<script data-main="../script/app/loginModule" src="../script/thirdParty/require.js"></script>
loginModule.js里面包含了一个配置和一个模块定义:
/*global window, document */
require.config({
paths: {
"jquery": "../thirdParty/jquery-1.8.0.min",
"ajaxUtility": "./ajaxUtility",
"jquery.artDialog": "../../plugin/artDialog4.1.6/jquery.artDialog",
"jqueryTool": "./jqueryTool",
"login": "./login"
},
shim: {
"jquery.artDialog": {
deps: ["jquery"],
exports: "artDialog"
}
}
});
define("loginModule", ["jquery", "ajaxUtility", "dialog", "jqueryTool", "login"], function ($, ajaxUtility, dialog, jqueryTool, login) {
'use strict';
var locale = window.locale;
ajaxUtility.init(locale);
$(document).ready(function () {
login.init(ajaxUtility, dialog, jqueryTool, locale);
});
});
注意观察,我的loginModule是个模块,依赖了dialog模块。
dialog模块是我自己定义的另一个模块,它依赖jquery.artDialog模块。
而jquery.artDialog模块在shim中注明了依赖jquery。
现在看看依赖jquery.artDialog的模块dialog.js, 下面的数组中声明了依赖关系,参数使用了shim中exports导出的变量名。
define("dialog", ["jquery", "jquery.artDialog"], function ($, artDialog) {
'use strict';
return {
cancelText: "",
locale: "",
okText: "",
titleText: "",
// language should be either 'cn' or 'en'
init: function (locale) {
this.locale = locale;
if (locale === "cn") {
this.cancelText = "取消";
this.okText = "确定";
this.errorTitleText = "错误";
this.okTitleText = "信息";
} else {
this.cancelText = "Cancel";
this.okText = "OK";
this.errorTitleText = "Error";
this.okTitleText = "Info";
}
},
error: function (message) {
$.dialog({
title: this.errorTitleText,
icon: "error",
content: message,
okVal: this.cancelText,
ok: function () {
this.close();
}
});
},
done: function (message) {
$.dialog({
title: this.okTitleText,
icon: "ok",
content: message,
okVal: this.okText,
ok: function () {
this.close();
}
});
}
};
});
用好RequireJS需要耐心,配置这玩意儿,光靠看文档还要结合自己的实际情况反复实验才行。
顺便知道了每个页面的requireJS配置只需要在top level也就是html页面直接引用的那个js文件中添加require.config... 即可。其他的js文件里就不需要了。
如果有多个页面,显然需要多个这样的top level 文件。有人叫做bootstrap,名字也很合适。