According to the way of requireJS, simulate simple relationship dependencies and asynchronous loading of resources

------------------------The first step is to implement the core logic of require------------------- ---------
(function(self){

self.exports = {};

function getDepArry(arg){
return typeof arg == "string" ? [arg] : arg;
};
/**-- ------------- Simulate jquery instance construction start----------------------*/

function ScriptNode(){
return new ScriptNode .prototype.init();
};
ScriptNode.prototype.init = function(){
return this;
}
ScriptNode.prototype.getInstance = function(url,fn){//Implement the factory pattern of
$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)

------------The second step implements the first dependency file module1.js---------- --------------
exports.define = {
topic: 'my export module1',
desc: 'this is other way to define ',
sayHello: function() {
console.log('topic ' + this.topic + this.desc);
}
}
----------------------The third step implements the second dependency file 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>

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326609495&siteId=291194637