通过上一篇DEMO的运行结果截图,我们可以看出,在index.jsp页面上,我们只是引入bootstrap.js这个文件,页面加载时候bootstrap.js会帮助我们自动判断加载ext-all-*.js的文件。
那么它是怎么确定要引用哪个ExtJS文件的呢?我们的目录中有分别有三个文件:
ext-all-debug.js:用于调试时引用
ext-all-dev.js:用于开发时引用
ext-all.js:在发布时引用
我们可以查看bootstrap.js的源代码一探究竟:
/**
* Load the library located at the same path with this file
*
* Will automatically load ext-all-dev.js if any of these conditions is true:
* - Current hostname is localhost
* - Current hostname is an IP v4 address
* - Current protocol is "file:"
*
* Will load ext-all.js (minified) otherwise
*/
从文件注释可以知道信息:
/**
* 加载本文件相同路径中的库
*
* 满足以下条件将自动加载 ext-all-dev.js:
* - 当前主机名是 localhost
* - 当前主机名是 IP v4 地址
* - 当前协议是 "file:"
*
* 其它情况下将加载 ext-all.js (minified)
*/
因为我们本地开发发布的地址路径必然是localhost,所有自动加载的就是ext-all-dev.js文件。上篇被我修改成debug模式啦。
(function() {
var scripts = document.getElementsByTagName('script'),
localhostTests = [
/^localhost$/,
/\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(:\d{1,5})?\b/ // IP v4
],
host = window.location.hostname,
isDevelopment = null,
queryString = window.location.search,
test, path, i, ln, scriptSrc, match;
for (i = 0, ln = scripts.length; i < ln; i++) {
scriptSrc = scripts[i].src;
match = scriptSrc.match(/bootstrap\.js$/);
if (match) {
path = scriptSrc.substring(0, scriptSrc.length - match[0].length);
break;
}
}
if (queryString.match('(\\?|&)debug') !== null) {
isDevelopment = true;
}
else if (queryString.match('(\\?|&)nodebug') !== null) {
isDevelopment = false;
}
if (isDevelopment === null) {
for (i = 0, ln = localhostTests.length; i < ln; i++) {
test = localhostTests[i];
if (host.search(test) !== -1) {
isDevelopment = true;
break;
}
}
}
if (isDevelopment === null && window.location.protocol === 'file:') {
isDevelopment = true;
}
document.write('<script type="text/javascript" charset="UTF-8" src="' +
path + 'ext-all' + (isDevelopment ? '-debug' : '') + '.js"></script>');
})();
源代码解读:
1、首先使用getElementsByTagName获取页面中所有带有script标记的元素,然后从中找出带有bootstrap.js的标记,将bootstrap.js的相对路径取出来保存在path中。
2、判断url的参数中是否有“debug”字符,例如,出现http://localhost/index.html? debug,则设置isDevelopment 为true。否则检测是否有“nodebug”字符,如果有,设置为false。如果以上两个条件都不符合,isDevelopment 还是初始值null,就要判断url的域名是否是“localhost”或IPv4地址,如果是,则isDevelopment设置为true。
3、如果isDevelopment是null且当前的url的协议是“file:”,则将isDevelopment 设置为true。如果isDevelopment为true时,则加载ext-all-debug.js文件,否则加载ext-all.js文件。
通过bootstrap.js,可自动控制加载ext-all-debug.js文件或ext-all.js文件,不用我们自己去修改script标记,非常方便。但如果你觉得自己修改方便,也可以使用Ext JS旧版的方式加载脚本文件。
来源:oschina
链接:https://my.oschina.net/u/112937/blog/277687