最初设想

require.js

var es = {};
es.each = function(arr, fn) {
  var i = 0;
  while(arr.length !== i) {
    fn(i, arr[i]);
    i++;
  }
};
var count = 0;
var cache = {};
var module = {};
module.exports = null;
var arr = [];
var require = function(m, cb) {
  while(m[0]) {

    var js = document.createElement('script');
    js.src = m[0];
    js.id = m[0];
    js.charset = 'utf-8';
    document.querySelectorAll('head')[0].appendChild(js);

    count++;
    js.onload = function() {
      count--;
      if (count === 0) {
        es.each(arr, function(i, cb) {
          cb(require, module.exports, module);
          arr[i] = module.exports;
        });
        cb.apply(null, arr)
      }
    };
    m.shift();
  }
}

var define = function(cb) {
  var id = document.currentScript.id;
  cache[id] = {
    status: 'loading',
    callback: cb
  };
  arr.push(cb);
};

require(['a.js', 'b.js'], function(a, b) {
  console.log(a);// aaa
  console.log(b);// bbb
});

a.js

define(function(require, exports, module) {
  module.exports = 'aaa';
});

b.js

define(function(require, exports, module) {
  module.exports = 'bbb';
});

erichooooow
229 声望5 粉丝

simple is not easy