根據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>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章