依赖加载策略

模块数据初始化

status状态生命周期

代码展示
demo包括4个文件, index.html , a.js , b.js , startUp.js
index.html
<!DOCTYPE html>
<html>
<head>
<title>自研模块加载器</title>
</head>
<body>
<script src="./startUp.js"></script>
<script>
startUp.use(['a.js', 'b.js'], function() {
console.log('startUp...')
})
</script>
</body>
</html>
a.js
define(function(require, exports, module) {
var a = {
who: "我"
}
exports(a)
})
b.js
define(function(require, exports, module) {
var b = {
text: "太难了"
}
exports(b)
})
startUp.js (模块加载器)
(function(global) {
var startUp = global.startUp = {
version: '1.0.1'
}
var data = {}; // 获取当前模块加载器内置信息
var cache = {}; // 缓存
//模块的生命周期
var status = {
FETCHED: 1,
SAVED: 2,
LOADING: 3,
LOADED: 4,
EXECUTING: 5,
EXECUTED: 6
}
// 静态工具类,判断是否为数组
var isArray = function(obj) {
return toString.call(obj) === "[object Array]";
}
// 构造函数
function Module(uri, deps) {
this.uri = uri;
this.deps = deps || []; // ['a.js', 'b.js'] 依赖项
this.exports = null;
this.status = 0;
this._waitings = {};
this._remain = 0;
}
// 分析主干(左子树,右子树)上的依赖
Module.prototype.load = function (){
var m = this;
m.status = status.LOADING; // 设置构造函数的状态为 LOADING => 3
}
// 资源定位
Module.prototype.resolve = function(){
}
/*
* 模块的静态属性和方法
*/
// 模块定义
Module.define = function (factory) {
}
// 检测缓存对象是否有当前模块信息
Module.get = function (uri, deps) {
return cache[uri] || (cache[uri] = new Module(uri, deps));
}
Module.use = function (deps, callback, uri) {
var m = Module.get(uri, isArray(deps) ? deps : [deps]);
console.log(m)
// 模块加载完成执行回调
m.callback = function() {
}
m.load();
}
var _cid = 0;
function cid() {
return _cid++;
}
// 初始化预加载资源
data.preload = [];
// 获取当前文档的URL
data.cwd = document.URL.match(/[^?]*\//)[0];
Module.preload = function(callback) {
var length = data.preload.length;
if(!length) callback();
}
// 入口函数
startUp.use = function(list, callback){
// 检测有没有预加载模块
Module.preload(function() {
Module.use(list, callback, data.cwd + "_use" +cid()) // 虚拟根目录
})
}
global.define = Module.define;
})(this)
来源:https://www.cnblogs.com/zzd0916/p/12240236.html