-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinclude.js
75 lines (68 loc) · 1.56 KB
/
include.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
/**
*用法:
* include.js([[url,callback], ...]); include.js([url, ...]);
* include.css([url]);
*/
var include = function (window) {
function loadScript(url, callback) {
var script = document.createElement("script");
if("onload" in script) {
script.async = "async";
script.src = url;
script.onload = function () {
releaseMemory();
if(callback)callback();
};
script.onerror = function (err) {
releaseMemory();
console.warn("load script error", err);
};
}else {
// IE8及之前
script.onreadystatechange = function () {
if (/loaded|complete/.test(script.readyState)) {
if(callback)callback();
}
}
}
document.body.appendChild(script);
//避免内存泄露
function releaseMemory() {
script.onload = script.onerror = script.onreadystatechange = null;
document.body.removeChild(script)
script = null;
};
};
function loadCss(url) {
var link = document.createElement("link");
link.rel = "stylesheet";
link.type = "text/css";
link.href = url;
document.getElementsByTagName("head")[0].appendChild(link);
};
// 判断对象类型
function type(obj) {
return Object.prototype.toString.call(obj).slice(8, -1);
};
//解析传进来什么东西
function jsParser(item) {
switch (type(item)) {
case "Array":
return loadScript(item[0], item[1]);
case "String":
return loadScript(item);
}
};
return {
js: function(item) {
while(item.length) {
jsParser(item.shift());
}
},
css: function() {
while(item.length) {
loadCss(item.shift());
}
}
}
}(window);