Require.js笔记
一、类型一(简单型)
文件位置
1、在页面尾部引入require.js,data-main加载主模块
<script src="js/require.js" data-main="js/main.js"></script>
2、
创建main.js
require.config({ baseUrl : "js", //路径 paths : { "jquery" : "./lib/jquery", //前面是命名,后面是文件名 "lazyload" : "./lib/lazy-load", "stickup" : "./lib/stick-up", "totop" : "./lib/to-top" } }); require(["jquery","stickup","lazyload","totop"],function($,stickup,lazyload,totop){ //回调函数 里需要将前面的参数传进来以便调用 StickUp.init(); lazyLoad.init(); ToTop.init(); })
3、打开stickup.js lazyload.js totop.js ,用define()封装下
由于这些模块都是用对象写的,需要用function封装。
另外 非规范模块
require.config({ shim: { 'underscore':{ exports: '_' }, 'backbone': { deps: ['underscore', 'jquery'], exports: 'Backbone' } } });
二、类型二(复杂型)
<script type="text/javascript" src="js/config.js"></script> <script src="js/require.js" data-main="js/demo.js"></script>
config.js
var requireConfig = { baseUrl : "./js", paths : { 'jquery' : "./lib/jquery", 'template' : './lib/template', 'layer' : "./lib/layer/layer" , 'DatePicker':"./lib/My97DatePicker/WdatePicker", 'selectize' : "./lib/selectize/selectize", }, packages : [ { name : 'component', location : './component', main : 'component' }, { name: 'easyUI', location: 'lib/easyui/js', main : 'easyUI' } ], shim:{ layer :{ deps : ['jquery'], exports: 'window.layer' }, bootstrap :['jquery'], selectize :['jquery'], cookie : ['jquery'], multiple : ['jquery'], 'easyUI/easyuizhCN':{ deps : ['jquery'] }, ztreeall:{ deps : ['jquery'] }, tooltipster:['jquery'] , ajaxfileupload:{ deps : ['jquery'] }, remoteCall:{ deps : ['jquery'] } } };
demo.js
require.config(requireConfig); require([ 'jquery',"component/chartComponent",],function($,chartComponent) { $(document).ready(function(){ });
main.js
require.config(requireConfig); require([ 'jquery',"component/zSearchComponent","component/curmbs","component/zUtil","layer"], function($,zSearchComponent,curmb,util) { layer.config({ path:'./js/lib/layer/', //layer.js所在的目录,可以是绝对目录,也可以是相对目录 extend: ['skin/espresso/style.css'] //加载新皮肤 }); $(document).ready(function(){ }); });