-
Notifications
You must be signed in to change notification settings - Fork 0
/
scriptLoader.js
107 lines (98 loc) · 2.77 KB
/
scriptLoader.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
100
101
102
103
104
105
106
107
// Nice script loader from here: https://stackoverflow.com/questions/538745/how-to-tell-if-a-script-tag-failed-to-load
var scriptLoader= function() {}
scriptLoader.prototype = {
timer: function(
times, // number of times to try
delay, // delay per try
delayMore, // extra delay per try (additional to delay)
test, // called each try, timer stops if this returns true
failure, // called on failure
result // used internally, shouldn't be passed
) {
var me = this;
if (times == -1 || times > 0) {
setTimeout(function() {
result = test() ? 1 : 0;
me.timer(
result ? 0 : times > 0 ? --times : times,
delay + (delayMore ? delayMore : 0),
delayMore,
test,
failure,
result
);
}, result || delay < 0 ? 0.1 : delay);
} else if (typeof failure == "function") {
setTimeout(failure, 1);
}
},
addEvent: function(el, eventName, eventFunc) {
if (typeof el != "object") {
return false;
}
if (el.addEventListener) {
el.addEventListener(eventName, eventFunc, false);
return true;
}
if (el.attachEvent) {
el.attachEvent("on" + eventName, eventFunc);
return true;
}
return false;
},
// add script to dom
require: function(url, args) {
var me = this;
args = args || {};
var scriptTag = document.createElement("script");
var headTag = document.getElementsByTagName("head")[0];
if (!headTag) {
return false;
}
setTimeout(function() {
var f = typeof args.success == "function" ? args.success : function() {};
args.failure = typeof args.failure == "function"
? args.failure
: function() {};
var fail = function() {
if (!scriptTag.__es) {
scriptTag.__es = true;
scriptTag.id = "failed";
args.failure(scriptTag);
}
};
scriptTag.onload = function() {
scriptTag.id = "loaded";
f(scriptTag);
};
scriptTag.type = "text/javascript";
scriptTag.async = typeof args.async == "boolean" ? args.async : false;
scriptTag.charset = "utf-8";
me.__es = false;
me.addEvent(scriptTag, "error", fail); // when supported
// when error event is not supported fall back to timer
me.timer(
15,
1000,
0,
function() {
return scriptTag.id == "loaded";
},
function() {
if (scriptTag.id != "loaded") {
fail();
}
}
);
scriptTag.src = url;
setTimeout(function() {
try {
headTag.appendChild(scriptTag);
} catch (e) {
fail();
}
}, 1);
}, typeof args.delay == "number" ? args.delay : 1);
return true;
}
};