使用requirejs实现include功能
使用过boostrap系列的人,都有一个不爽的地方:每个bootstrap的组件都包含一系列css样式,如果我们一个页面使用2个以上组件,则需要同时引入4行以上代码,比如:
为了节省代码和修改的方便,则我们首先会想到像<jsp:include />那样,将这些语句写到一个 resource.html文件中,其他页面直接“include”即可。不幸的是,目前为止除了 chrome等少数主流浏览器支持<link rel="import" href="resource.html">外,IE、firefox等均不支持。所幸的是,著名的requirejs AMD支持javascript的import功能,可以实现同样的效果。
1、首先,新建文件 resource.js
require.config({
baseUrl: '/sumpay-sms/',
paths: { //js-files alias
"jquery": "webjars/jquery/2.1.4/jquery.min",
"i18n": "webjars/jquery-i18n-properties/1.2.2/jquery.i18n.properties.min",
"bootstrap": "webjars/bootstrap/3.3.5/js/bootstrap.min",
"validator": "webjars/bootstrapvalidator/0.5.3/js/bootstrapValidator.min",
"validator-cn": "webjars/bootstrapvalidator/0.5.3/js/language/zh_CN",
"bootstrap-table": "webjars/bootstrap-table/1.9.1-1/bootstrap-table.min",
"bstable-cn": "webjars/bootstrap-table/1.9.1-1/locale/bootstrap-table-zh-CN.min",
index: "js/common"
},
map: {
'*': { //all modules
"css": "css.min.js",
"text": "text.js",
}
},
shim: { //css只能定义在这里
"i18n": {
deps: ['jquery']
},
"bootstrap": {
deps: ['i18n', "css!webjars/bootstrap/3.3.5/css/bootstrap.min","css!/sumpay-sms/css/index"],
},
"validator": {
deps: ['i18n', 'css!webjars/bootstrapvalidator/0.5.3/css/bootstrapValidator.min'],
},
"validator-cn": {
deps: ['validator', "bootstrap"],
},
"bootstrap-table": {
deps:['i18n', "bootstrap", "css!webjars/bootstrap-table/1.9.1-1/bootstrap-table.min"],
},
"bstable-cn": {
deps:["bootstrap-table"],
},
},
waitSeconds: 50
});
2、其次,在业务系统的页面(test.html)
<script src="require.js" data-main="test.js"></script>
</head>
<table id="template-list" class="table">
<!--tr>
<th data-field="templCode">aaaa</th>
<th data-field="templName">bbb</th>
<th data-field="content">cccc</th>
</tr-->
</table>
3、新建 test.js脚本
require(["resource"], function(resource){ //find -> resource.js
"use strict";
require(["bstable-cn"], function () { //module: bstable-cn & its dependencies
$("#template-list").bootstrapTable({
columns: [{
field: 'Id',
title: '编号'
},{
field: 'Name',
title: '姓名'
},{
field: 'Type',
title: '类型'
},{
field: 'Time',
title: '时间'
}]
});
$("#delcfmModel").modal("show");
});
});
至此,全部完成。注意,使用嵌套require函数。
吐槽一下 requirejs,所有的页面事件(脚本),都必须写在require(["jquery","bootstrap"], callback)的回调函数中,不能像以前那样随意地用代码块来实现。