模块化管理组件(2012/05/09)
模块化管理组件,同上,新手慎用,仅供学习:
(function(ns) {
Require = {};
Require.globals = {
anonymousMod: null,
loadedUris: {}
}
Require.fn = {
loadScript: function(uri, callback) {
var __self__ = this,
head = document.head || document.getElementsByTagName('head')[0] || document.documentElement,
node = document.createElement("script");
node.src = uri + ".js";
node.onload = node.onerror = node.onreadystatechange = function() {
if (/loaded|complete|undefine/.test(node.readyState)) {
node.onload = node.onerror = node.onreadystatechange = null;
if (node.parentNode) {
node.parentNode.removeChild(node);
}
var mod = Require.anonymousMod;
if (mod) {
if (!Require.globals.loadedUris[uri]) {
__self__.memoize(uri, mod);
}
Require.anonymousMod = null;
}
callback && callback();
}
}
head.appendChild(node);
},
Module: function(id, deps, mod) {
this.id = id;
this.deps = deps;
this.mod = mod;
},
memoize: function(uri, mod) {
mod.id = uri;
Require.globals.loadedUris[uri] = mod;
},
define: function(requires, mod) {
var id = undefined,
deps = requires,
mod = mod;
var mod = new Require.fn.Module(id, deps, mod);
Require.anonymousMod = mod;
},
setReadyState: function(uris) {
for (var i = 0, l = uris.length; i < l; i++) {
var el = Require.globals.loadedUris[uris[i]];
if (el) {
el.ready = true;
if (el.mod) {
el.mod();
}
}
}
},
getUnReadyUris: function(uris) {
var unReadyUris = [];
for (var i = 0, l = uris.length; i < l; i++) {
var mod = Require.globals.loadedUris[uris[i]];
if (!mod || ! mod.ready) {
unReadyUris.push(uris[i]);
}
}
return unReadyUris;
},
provide: function(uris, callback) {
var unReadyUris = this.getUnReadyUris(uris),
fn = arguments.callee,
__self__ = this;
for (var i = 0, l = unReadyUris.length, n = l; i < l; i++) { (function(uri) {
if (Require.globals.loadedUris[uri]) {
onload();
} else {
__self__.loadScript(uri, onload);
}
function onload() {
var mod = Require.globals.loadedUris[uri];
if (mod) {
var deps = mod.deps;
var m = deps.length;
if (m) {
n += m;
fn.call(__self__, deps, function() {
n -= m;
if (n === 0) onProvide(mod);
});
}
}
if (--n === 0) onProvide(mod);
}
})(unReadyUris[i])
}
function onProvide(mod) {
__self__.setReadyState(unReadyUris);
callback();
}
}
}
ns.require = function(uris, callback) {
Require.fn.provide(uris, function() {
var args = [],
el;
for (var i = 0, l = uris.length; i < l; i++) {
el = Require.globals.loadedUris[uris[i]];
if (el && el.mod) {
args.push(el.mod());
}
}
callback && callback.apply(null, args);
});
}
ns.define = Require.fn.define;
})(this);