1.无依赖情况

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>一步步走入AMD</title>
<script> var req = {};
/*无依赖*/
req.config = {
"a":{
deps:[],
fn:function(){
console.log("a");
}
},
"b":{
deps:[],
fn:function(){
console.log("b");
}
},
"c":{
deps:[],
fn:function(){
console.log("c");
}
},
}
var require = function(deps,fn){
var config = req.config,
deps_arr = []; // 1.找依赖,生成依赖数组
for(var i=0,l = deps.length; i<l; i++){
var deps_item = deps[i];
deps_arr.push(config[deps_item].fn);
} // 2.依赖数组,是入口函数的参数
fn.apply(window,deps_arr);
}; require(["a","b"],function(a,b){
a();
b();
});
</script>
</head>
<body> </body>
</html>

2.有依赖

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>不要温柔地走入AMD</title>
<script>
var req = {};
/*有依赖*/
req.config = {
"a":{
deps:["b"],
fn:function(b){
return function(){
console.log("a");
b();
} }
},
"b":{
deps:["c"],
fn:function(c){
return function(){
console.log("b");
c();
} }
},
"c":{
deps:[],
fn:function(){
var private_c = "cc"
return function(){
console.log("c");
console.log(private_c);
} }
}
}
var require = function(deps,fn){
var config = req.config,
deps_arr = []; var excute_obj = {},
deps_chain = []; for(var i in config){
deps_chain.push(i);
} // 包装各个依赖函数
deps_chain.forEach(function(configName){
var item = config[configName],
item_deps = item["deps"],
item_fn = function(){
return item["fn"].apply(window,excute_obj[configName]["deps"])();
};
excute_obj[configName] = {};
excute_obj[configName]["fn"] = item_fn; }); // 依赖函数的执行参数生成
deps_chain.forEach(function(configName){
var item = config[configName],
item_deps = item["deps"],
param_arr = []; item_deps.forEach(function(i){
param_arr.push(excute_obj[i]["fn"]);
}); excute_obj[configName]["deps"] = param_arr; }); console.log(excute_obj); deps.forEach(function(configName){
deps_arr.push(excute_obj[configName]["fn"]);
}); fn.apply(window,deps_arr);
}; // bug:依赖设置错误
require(["a"],function(a){
a(); });
</script>
</head>
<body> </body>
</html>

3.循环依赖判断

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>不要温柔地走入AMD</title>
<script>
var req = {};
/*有循环依赖*/
req.config = {
"a":{
deps:["b","c"],
fn:function(b,c){
return function(){
console.log("a");
b();
c();
} }
},
"b":{
deps:["c"],
fn:function(c){
return function(){
console.log("b");
c();
} }
},
"c":{
deps:["a"],
fn:function(){
return function(){
console.log("c");
} }
}
}
var require = function(deps,fn){
var config = req.config,
deps_arr = []; var excute_obj = {},
deps_chain = []; for(var i in config){
deps_chain.push(i);
}
console.log(deps_chain); function arrayClone(arr){
var _array = [];
for(var i=0,l=arr.length; i<l; i++){
_array.push(arr[i]);
} return _array;
}
function loopDepJudge(currentKey,currentDeps, circleArr){
var check_arr = [];
check_arr.unshift(arrayClone(currentDeps) ); var keyChain = [currentKey];
// 开始循环
(function(){
var currentDeps = check_arr[0];
// console.log(currentDeps);
if(currentDeps.length > 0){
var nextKey = currentDeps.shift(),
nextDeps = circleArr[nextKey];
if(keyChain.indexOf(nextKey) > -1){
keyChain = [false,nextKey,keyChain.pop()];
return;
}
else{
keyChain.push(nextKey);
} if(nextDeps.length > 0){
check_arr.unshift(arrayClone(nextDeps));
}
else{
check_arr.shift();
keyChain = [currentKey];
if(check_arr.length == 0){
return;
}
}
}
else{
return;
}
arguments.callee();
})();
return keyChain;
} (function(){
// 循环依赖检测
var circle_deps = {};
deps_chain.forEach(function(configName){
circle_deps[configName] = config[configName]["deps"];
}); deps_chain.forEach(function(configName){
var key = configName,
deps = arrayClone(circle_deps[key]); var keyChain = loopDepJudge(key,deps,circle_deps);
if(keyChain[0] == false){
throw new Error("有循环依赖。他们是"+keyChain[1]+"和" +keyChain[2]);
}
else{
console.log(keyChain)
}
});
// var keyChain = loopDepJudge() // 包装各个依赖函数
deps_chain.forEach(function(configName){
var item = config[configName],
item_deps = item["deps"],
item_fn = function(){
return item["fn"].apply(window,excute_obj[configName]["deps"])();
}; excute_obj[configName] = {};
excute_obj[configName]["fn"] = item_fn; }); // 依赖函数的执行参数生成
deps_chain.forEach(function(configName){
var item = config[configName],
item_deps = item["deps"],
param_arr = []; item_deps.forEach(function(i){
param_arr.push(excute_obj[i]["fn"]);
}); excute_obj[configName]["deps"] = param_arr; }); console.log(excute_obj); })(); deps.forEach(function(configName){
deps_arr.push(excute_obj[configName]["fn"]);
}); fn.apply(window,deps_arr);
}; require(["a"],function(a){
a(); });
</script>
</head>
<body> </body>
</html>

4.define函数定义

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>不要温柔地走入AMD</title>
<script>
var req = {};
/*define函数定义*/
req.requireConfig = {}; var define = function(deps,fn){
var protocal = location.protocal,
host = location.host,
port = location.port,
pathName = location.pathname,
href = location.href, paths = req.userConfig.paths,
baseUrl = req.userConfig.baseUrl || ""; function baseUrlParse(baseUrl){
var str_length = baseUrl.length,
newBaseUrl = "";
if(baseUrl.lastIndexOf("/") == str_length -1){ }
else{
newBaseUrl = baseUrl + "/";
}
return newBaseUrl;
} // 不支持IE
// 1.获取当前js文件地址
var scriptSrc = document.currentScript.src; for (var i in paths) {
var path = paths[i],
complete_path = ""; // 2. 生成complete_path var backslash_pos = href.lastIndexOf("/"),
slash_href = href.substring(0,backslash_pos+1),
complete_path = slash_href + baseUrlParse(baseUrl) + path; // 3. 根据文件地址进行匹配,从而生成req.requireConfig
if(scriptSrc == complete_path){
req.requireConfig[i] = {
"deps":deps,
"fn":fn
};
}
};
};
var require = function(deps,fn){
function arrayClone(arr){
var _array = [];
for(var i=0,l=arr.length; i<l; i++){
_array.push(arr[i]);
} return _array;
}
function loopDepJudge(currentKey,currentDeps, circleArr){
var check_arr = [];
check_arr.unshift(arrayClone(currentDeps) ); var keyChain = [currentKey];
// 开始循环
(function(){
var currentDeps = check_arr[0];
// console.log(currentDeps);
if(currentDeps.length > 0){
var nextKey = currentDeps.shift(),
nextDeps = circleArr[nextKey];
if(keyChain.indexOf(nextKey) > -1){
keyChain = [false,nextKey,keyChain.pop()];
return;
}
else{
keyChain.push(nextKey);
} if(nextDeps.length > 0){
check_arr.unshift(arrayClone(nextDeps));
}
else{
check_arr.shift();
keyChain = [currentKey];
if(check_arr.length == 0){
return;
}
}
}
else{
return;
}
arguments.callee();
})();
return keyChain;
} var config = req.requireConfig,
deps_arr = [],
excute_obj = {},
deps_chain = []; for(var i in config){
deps_chain.push(i);
} // 循环依赖检测
(function(){
var circle_deps = {};
deps_chain.forEach(function(configName){
circle_deps[configName] = config[configName]["deps"];
}); deps_chain.forEach(function(configName){
var key = configName,
deps = arrayClone(circle_deps[key]); var keyChain = loopDepJudge(key,deps,circle_deps);
if(keyChain[0] == false){
throw new Error("有循环依赖。他们是"+keyChain[1]+"和" +keyChain[2]);
}
else{
console.log(keyChain)
}
});
})();// 包装各个依赖函数
deps_chain.forEach(function(configName){
var item = config[configName],
item_deps = item["deps"],
item_fn = function(){
return item["fn"].apply(window,excute_obj[configName]["deps"])();
};
excute_obj[configName] = {};
excute_obj[configName]["fn"] = item_fn; }); // 依赖函数的参数数组生成
deps_chain.forEach(function(configName){
var item = config[configName],
item_deps = item["deps"],
param_arr = []; item_deps.forEach(function(i){
param_arr.push(excute_obj[i]["fn"]);
}); excute_obj[configName]["deps"] = param_arr; }); // 主函数的参数数组生成
deps.forEach(function(configName){
deps_arr.push(excute_obj[configName]["fn"]);
}); fn.apply(window,deps_arr);
}; req.userConfig = {
"baseUrl":"",
"paths":{
"a":"a.js",
"b":"b.js",
"c":"c.js"
}
};
</script>
<script type="text/javascript" src="b.js"></script>
<script type="text/javascript" src="a.js"></script>
<script type="text/javascript" src="c.js"></script>
<script>
require(["a"],function(a){
a();
});
</script>
</head>
<body> </body>
</html>

5.js加载器生成

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>不要温柔地走入AMD</title>
<script>
/*
1.暂不支持shim
*/
var req = {}; req.requireConfig = {};
req.userConfig= {};
// 用来记录js加载的数目
req.jsLoadCount = 0; function baseUrlParse(baseUrl){
var str_length = baseUrl.length,
newBaseUrl = "";
if(baseUrl.lastIndexOf("/") == str_length -1){ }
else{
newBaseUrl = baseUrl + "/";
}
return newBaseUrl;
} function getObjSize(obj){
var size = 0;
for(var i in obj){
var item = obj[i];
if(item !== null && typeof(item) !== "undefined"){
size++;
}
} return size;
} var define = function(deps,fn){
var protocal = location.protocal,
host = location.host,
port = location.port,
pathName = location.pathname,
href = location.href, paths = req.userConfig.paths,
baseUrl = req.userConfig.baseUrl || ""; // 不支持IE
// 1.获取当前js文件地址
var scriptSrc = document.currentScript.src; for (var i in paths) {
var path = paths[i],
complete_path = ""; // 2. 生成complete_path
var backslash_pos = href.lastIndexOf("/"),
slash_href = href.substring(0,backslash_pos+1),
complete_path = slash_href + baseUrlParse(baseUrl) + path; // 3. 根据文件地址进行匹配,从而生成req.requireConfig
if(scriptSrc == complete_path){
req.requireConfig[i] = {
"deps":deps,
"fn":fn
};
}
};
};
var require = function(deps,fn){
// 检测js加载完毕与否
var timer_loader = setTimeout(function(){
if(req.jsLoadCount == 0){
clearTimeout(timer_loader);
mainRequire();
}
else{
timer_loader();
}
},200); function mainRequire(){
function arrayClone(arr){
var _array = [];
for(var i=0,l=arr.length; i<l; i++){
_array.push(arr[i]);
} return _array;
}
function loopDepJudge(currentKey,currentDeps, circleArr){
var check_arr = [];
check_arr.unshift(arrayClone(currentDeps) ); var keyChain = [currentKey];
// 开始循环
(function(){
var currentDeps = check_arr[0];
// console.log(currentDeps);
if(currentDeps.length > 0){
var nextKey = currentDeps.shift(),
nextDeps = circleArr[nextKey];
if(keyChain.indexOf(nextKey) > -1){
keyChain = [false,nextKey,keyChain];
return;
}
else{
keyChain.push(nextKey);
} if(nextDeps.length > 0){
check_arr.unshift(arrayClone(nextDeps));
}
else{
check_arr.shift();
keyChain = [currentKey];
if(check_arr.length == 0){
return;
}
}
}
else{
return;
}
arguments.callee();
})();
return keyChain;
}
var config = req.requireConfig,
deps_arr = [],
excute_obj = {},
deps_chain = []; for(var i in config){
deps_chain.push(i);
}
console.log(config); // 循环依赖检测
(function(){
var circle_deps = {};
deps_chain.forEach(function(configName){
circle_deps[configName] = config[configName]["deps"];
});
console.log(circle_deps); deps_chain.forEach(function(configName){
var key = configName,
deps = arrayClone(circle_deps[key]); var keyChain = loopDepJudge(key,deps,circle_deps);
if(keyChain[0] == false){
throw new Error("前方高能,有循环依赖。他们是"+keyChain[1]+"和" +keyChain[2]);
}
else{
console.log(keyChain)
}
});
})(); // 包装各个依赖函数
deps_chain.forEach(function(configName){
var item = config[configName],
item_deps = item["deps"],
item_fn = function(){
return item["fn"].apply(window,excute_obj[configName]["deps"])();
};
excute_obj[configName] = {};
excute_obj[configName]["fn"] = item_fn; }); // 依赖函数的参数数组生成
deps_chain.forEach(function(configName){
var item = config[configName],
item_deps = item["deps"],
param_arr = []; item_deps.forEach(function(i){
param_arr.push(excute_obj[i]["fn"]);
}); excute_obj[configName]["deps"] = param_arr; }); // 主函数的参数数组生成
deps.forEach(function(configName){
deps_arr.push(excute_obj[configName]["fn"]);
}); fn.apply(window,deps_arr);
}
};
require.config = function(config_obj){
req.userConfig = config_obj;
req.jsLoadCount = getObjSize(config_obj.paths); function generateScript(url,loadCount){
var _script = document.createElement('script');
_script.type = 'text/javascript';
_script.charset = 'utf-8';
_script.async = true;
_script.src = url;
_script.onload = function(){
req.jsLoadCount--;
};
_script.onerror = function(e){
throw new Error(e);
}; var fs = document.getElementsByTagName('script')[0];
fs.parentNode.insertBefore(_script, fs);
}
var href = location.href,
baseUrl = req.userConfig.baseUrl || "";
paths = req.userConfig.paths;
for(var i in paths){
var path = paths[i],
backslash_pos = href.lastIndexOf("/"),
slash_href = href.substring(0,backslash_pos+1),
complete_path = slash_href + baseUrlParse(baseUrl) + path;
generateScript(complete_path);
} } require.config({
"baseUrl":"",
"paths":{
"c":"c.js?v=3",
"a":"a.js",
"b":"b.js"
}
}); require(["a","b"],function(a,b){
a();
b();
}); </script> </head>
<body> </body>
</html>

不要温柔地走入AMD的更多相关文章

  1. 不要温柔地走入promise

    第一步 <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title ...

  2. AngularJs2与AMD加载器(dojo requirejs)集成

    现在是西太平洋时间凌晨,这个问题我鼓捣了一天,都没时间学英语了,英语太差,相信第二天我也看不懂了,直接看结果就行. 核心原理就是require在AngularJs2编译过程中是关键字,而在浏览器里面运 ...

  3. js模块定义——支持CMD&AMD&直接加载

    /* animate */ //直接加载 (function() { var animate = {} //balabala window.animate = animate; })(); //AMD ...

  4. JavaSript模块规范 - AMD规范与CMD规范介绍

    JavaSript模块化   在了解AMD,CMD规范前,还是需要先来简单地了解下什么是模块化,模块化开发?       模块化是指在解决某一个复杂问题或者一系列的杂糅问题时,依照一种分类的思维把问题 ...

  5. AMD电脑装完Winsows10后开机蓝屏,报错代码:cdmsnroot_s.sys

    背景:今天装了个WIN10,电脑配置:联想 IdeaPad   Z485      : AMD   A8处理器      .完成安装后电脑没有问题,安装了驱动程序后将           电脑用360 ...

  6. JavaScript的模块化之AMD&CMD规范

    前端开发常常会遇到的问题: 1.恼人的命名冲突: 2.繁琐的文件依赖: 模块化开发的优势: 1.解决命名冲突和依赖管理: 2.模块的版本管理: 3.提高代码的可维护性: 4.前端性能优化: JavaS ...

  7. Javascript模块化编程(二):AMD规范

    Javascript模块化编程(二):AMD规范   作者: 阮一峰 原文地址:http://www.ruanyifeng.com/blog/2012/10/asynchronous_module_d ...

  8. CommonJS, AMD 和 RequireJS之间的关系(转载)

    先说说CommonJS CommonJS - 大家是不是觉得JavaScript仅仅是一个客户端的编译语言,其实JavaScript设计之初不仅仅是针对客户端设计的语言.后来只是由于Web的迅速流行, ...

  9. Can't load IA 32-bit .dll on a AMD 64-bit platform错误的解决

    64位的系统,64位的myeclipse,64位的jdk,64位的tomcat,结果报错:Can't load IA 64-bit .dll on a AMD 32-bit platform,简直无语 ...

随机推荐

  1. 【python cookbook】【字符串与文本】13.对齐文本字符串

    问题:以某种对齐方式将文本做格式化处理 解决方案: 1.针对字符串:ljust().rjust().center()方法 2.针对任何值,更加通用的:format()  更多内容:https://do ...

  2. 内存映射MMAP和DMA【转】

    转自:http://blog.csdn.net/zhoudengqing/article/details/41654293 版权声明:本文为博主原创文章,未经博主允许不得转载. 这一章介绍Linux内 ...

  3. 分析Linux内核创建一个新进程的过程【转】

    转自:http://www.cnblogs.com/MarkWoo/p/4420588.html 前言说明 本篇为网易云课堂Linux内核分析课程的第六周作业,本次作业我们将具体来分析fork系统调用 ...

  4. PHP笔记随笔

    1.CSS控制页面文字不能复制: body{-webkit-user-select:none;}   2.[php过滤汉字和非汉字] $sc="aaad....##--__i汉字过滤&quo ...

  5. 深入理解GCD(一)

    虽然 GCD 已经出现过一段时间了,但不是每个人都明了其主要内容.这是可以理解的:并发一直很棘手,而 GCD 是基于 C 的 API ,它们就像一组尖锐的棱角戳进 Objective-C 的平滑世界. ...

  6. php开启openssl的方法

    windows下开启方法: 1: 首先检查php.ini中:extension=php_openssl.dll是否存在, 如果存在的话去掉前面的注释符‘:’, 如果不存在这行,那么添加extensio ...

  7. 20145227《Java程序设计》第1次实验报告

    20145227<Java程序设计>第1次实验报告 实验步骤与内容 命令行下Java程序开发 1.打开 cmd ,输入 mkdir 20145227 命令建立实验目录,然后输入 cd 20 ...

  8. ACM题目————A simple problem

    Description Zty很痴迷数学问题..一天,yifenfei出了个数学题想难倒他,让他回答1 / n.但Zty却回答不了^_^. 请大家编程帮助他.   Input 第一行整数T,表示测试组 ...

  9. c#之线程

    //Process[] pro= Process.GetProcesses(); //foreach (var item in pro) //{ // Console.WriteLine(item); ...

  10. c#作业

    string a = this.textBox1.Text; // string [] b=a.Split("\r\n".ToCharArray(),StringSplitOpti ...