根据requireJS的方式,模拟简单的关系依赖和资源异步加载

------------------------第一步实现 require 核心逻辑----------------------------
(function(self){

self.exports = {};

function getDepArry(arg){
return typeof arg == "string" ? [arg] : arg;
};
/**---------------模拟jquery 实例构建 start----------------------*/

function ScriptNode(){
return new ScriptNode.prototype.init();
};
ScriptNode.prototype.init = function(){
return this;
}
ScriptNode.prototype.getInstance = function(url,fn){//实现$script的工厂模式
var $script = document.createElement('script');
$script.setAttribute('src', url);
$script.onload = fn;
return $script;
}
ScriptNode.prototype.init.prototype = ScriptNode.prototype

/**---------------模拟jquery 实例构建  end----------------------*/
function CreateElement4Head(){
var $node;
return function($script){
$node = $node || document.querySelector('head'); //实现$node的单例模式
$node.appendChild($script);
}
}
function require(deps,callback){
var arr = [];
var count = 0;
var depArry = getDepArry(deps);
var depsLength = depArry.length;
for(var i=0;i<depsLength;i++){
(function(i){
var $script = ScriptNode().getInstance(depArry[i],function(){
count++;
arr.push(self.exports);
self.exports = {};
if(count == depsLength){
callback && callback.apply(null,arr);
}
});
CreateElement4Head()($script);
})(i)
}
}
self.require = require;
})(window)

----------------------第二步实现 第一个依赖文件 module1.js------------------------
exports.define = {
topic: 'my export module1',
desc: 'this is other way to define ',
sayHello: function() {
console.log('topic ' + this.topic + this.desc);
}
}
----------------------第三步实现 第二个依赖文件 module2.js------------------------
exports.define = {
name: 'xm',
age: 22,
info: function() {
console.log('topic ' + this.name + this.age);
}
}
-----------------------第四步实现 编写测试文件------------------------------------
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="./require1.js"></script>
</head>
<body>
</body>
<script>
require(['./module1.js','./module2.js'], function(def, def2) {
   def.define.sayHello();
   def2.define.info();
});
</script>
</html>

猜你喜欢

转载自zgjlhnwj.iteye.com/blog/2378891
今日推荐