requirejs 笔记

index.html

<!doctype html>
<html>
    <head>
        <title>requirejs</title>
        <meta charset="utf-8">
        <script data-main="js/main" src="js/require.js"></script>
    </head>
    <body>

    </body>
</html>

main.js    合并js功能

require.config({
    // baseUrl: 'js/lib', 如果加载的这三个js不和main在一个目录下,就这样配置这个参数,或者直接写网址路径
    paths: {
        underscore: 'underscore.min',
        backbone:'backbone.min',
        jquery: 'jquery-1.9.1.min',
        math :'math'
    },
    /*
        shim属性,专门用来配置不兼容的模块。具体来说,每个模块要定义(1)exports值(输
        出的变量名),表明这个模块外部调用时的名称;(2)deps数组,表明该模块的依赖性。
    */
    shim: {
      'underscore':{
        exports: '_'
      },
      'backbone': {
        deps: ['underscore', 'jquery'],
        exports: 'Backbone'
      }

    }
/*jQuery的插件可以这样定义
    shim: {

    'jquery.scroll': {

      deps: ['jquery'],

      exports: 'jQuery.fn.scroll'

    }

  }
*/

});
 
// require(['jquery'], function($) {
//     alert($().jquery);
// });

require(['jquery', 'underscore', 'backbone'], function ($, _, Backbone){
  // some code here
    alert($().jquery);
});
// 如果不依赖其他模块
require(['math'],function(math){
    alert(math.add(1,2))
})
// domready插件,可以让回调函数在页面DOM结构加载完成后再运行。
require(['domready!'], function (doc){

    // called once the DOM is ready

});

/*
    require()函数接受两个参数。第一个参数是一个数组,表示所依赖的模块,
    上例就是['moduleA', 'moduleB', 'moduleC'],即主模块依赖这三个模块;第二个参数是一个回调函数,
    当前面指定的模块都加载成功后,它将被调用。加载的模块会以参数形式传入该函数,从而在回调函数内部就
    可以使用这些模块。
*/
/* 
    require()异步加载moduleA,moduleB和moduleC,浏览器不会失去响应;它指定的回调函数,只有前面的模块
    都加载成功后,才会运行,解决了依赖性的问题。
 */
/*
    1、data-main属性
    2、require.config方法
    3、require函数 
*/
View Code

math.js   自定的js

// 这种定义 是不依赖其他模块
define(function(){
    var add = function( x , y){
        return x+y ;
    }
    return{
        add : add
    }
});

// 否则 这样定义

// define(['mylib'],function(mylib){
//     function foo(){
//    mylib.doSomething();
//  }

// return {

//   foo : foo

//  };
// })
View Code
原文地址:https://www.cnblogs.com/jine/p/3817772.html