-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathaddJS.js
99 lines (86 loc) · 2.36 KB
/
addJS.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
/**
* @author xiaojue[[email protected]]
* @fileoverview 前端加载脚本,更新时间戳,切换debug,加载css
* @date 20150902
*/
(function(win, doc) {
var scripts = doc.getElementsByTagName('script'),
scriptsLen = scripts.length,
currentScript = scripts[scriptsLen - 1],
configScript = currentScript.getAttribute('data-config'),
Cache = currentScript.getAttribute('data-config-cache'),
timestamp = parseInt(Date.now() / (parseInt(Cache, 10) * 60 * 1000), 10);
function parseUrl(reg) {
return (reg).test(location.search);
}
function parseDebug() {
return parseUrl(/debug/);
}
function parseSass() {
return parseUrl(/sass/);
}
function parseES6() {
return parseUrl(/es6/);
}
function switchFile(path) {
var config = addjs.config,
debug = parseDebug();
if (debug && config.debugMap && config.debugMap[path]) {
var debugPath = config.debugServer + config.debugMap[path];
debugPath = parseSass() ? debugPath + '&sass=1' : debugPath;
debugPath = parseES6() ? debugPath + '&es6=1' : debugPath;
return debugPath;
} else {
return path;
}
}
function writeScript(src) {
doc.write('<script src="' + src + '"></script>');
}
function writeStyle(href) {
doc.write('<link href="' + href + '" rel="stylesheet">');
}
function getConfig(cb) {
if (addjs.config) {
cb(addjs.config);
} else {
writeScript(configScript + '?t=' + timestamp);
addjs.cbs.push(cb);
}
}
function addFile(path, func) {
getConfig(function(config) {
path = switchFile(path);
path = parseDebug() ? path : path + '?v=' + config.version;
func(path);
});
}
var addjs = {
_debug: false,
_configLoaded: false,
cbs: [],
css: function(path) {
addFile(path, writeStyle);
},
js: function(path) {
addFile(path, writeScript);
},
setConfig: function(options) {
var self = this;
if (!options.version) {
throw new Error('must have a version');
}
if (!options.debugServer) {
options.debugServer = 'http://127.0.0.1:7575/combine?filename=';
}
this.config = options;
this.cbs.forEach(function(func) {
if (!func.exec) {
func(self.config);
func.exec = true;
}
});
}
};
win.addjs = addjs;
})(window, document);