require.js 使得我们最简单的代码可以通过模块化来编写组件。下面是一个基本的结构。
目录
示例项目结构
JS引用顺序
require.js jquery和bootstrap引入顺序
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="UTF-8">
- <title>Insert title here</title>
- <script type="text/javascript" src="js/jquery/jquery-2.2.1.min.js"></script>
- <script type="text/javascript" src="js/require-2.1.11.mini.js"></script>
- <script type="text/javascript" src="js/bootstrap.min.js"></script>
- <link rel="stylesheet" href="css/bootstrap.min.css">
- <script type="text/javascript" src="app/index.js"></script>
- </head>
- <body>
- <button id="myRequire" class="btn btn-primary btn-lg" >require初始化调用</button>
- <button class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">bootstrap模态弹框</button>
- <!-- 模态框(Modal) -->
- <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
- <div class="modal-dialog">
- <div class="modal-content">
- <div class="modal-header">
- <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
- <h4 class="modal-title" id="myModalLabel">模态框(Modal)标题</h4>
- </div>
- <div class="modal-body">在这里添加一些文本</div>
- <div class="modal-footer">
- <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
- <button type="button" class="btn btn-primary">提交更改</button>
- </div>
- </div><!-- /.modal-content -->
- </div><!-- /.modal -->
- </div>
- </html>
定义模块组件
权限模块:app/permission/permission.js
- define(function(){
-
- console.info('permission');
-
- function init(){
- console.info('permission-init');
- }
-
- return {
- init:init
- }
- });
用户模块:app/user/user.js
- define(function(){
-
- console.info('user');
-
- function init(){
- console.info('user-init');
- }
-
- return {
- init:init
- }
- });
系统初始化模块:app/index.js
- require.config({
- urlArgs : "v=1.0",
- strict:"true",
- paths : {
- jquery:'js/jquery/jquery-2.2.1.min',
- // 系统业务功能
- user : 'app/user/user',
- permission : 'app/permission/permission',
-
- },
- waitSeconds : 0
- });
-
- require(['jquery','user','permission'],function($,user,permission){
-
- $("#myRequire").off('click').on('click',function(){
- alert("init");
- init();
- });
-
- function init(){
- user.init();
- permission.init();
- }
-
-
- return {
- init:init
- }
-
- });