-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathloader.js
77 lines (58 loc) · 2.07 KB
/
loader.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
(function(exports){
var getHandlerInvoker = function(evtType){
return function(e){
e.detail = this;
this.eventListeners[evtType].forEach(function(f){
f.call(window, e);
}.bind(this));
}.bind(this);
};
var Loader = function(fontFamily, url, extraCSSString, format){
this.eventListeners = {
'beforesend': [],
'progress': [],
'load': [],
'error': [],
'abort': []
};
this.xhr = new XMLHttpRequest();
this.xhr.addEventListener('progress', getHandlerInvoker.call(this, 'progress'));
this.xhr.addEventListener('load', function(e){
if(this.xhr.status.toString()[0] === '2'){
var blobURL = URL.createObjectURL(this.xhr.response);
var head = document.getElementsByTagName('head')[0];
var style = document.createElement('style');
style.setAttribute('type', 'text/css');
style.textContent = '\n' +
'@font-face{\n' +
' font-family: ' + fontFamily + ';\n' +
' src: url(\'' + blobURL + '\') format(\'' + format + '\');\n' +
(extraCSSString ? (' ' + extraCSSString + '\n') : '') +
'}\n';
head.appendChild(style);
}
getHandlerInvoker.call(this, 'load')(e);
}.bind(this));
this.xhr.addEventListener('abort', getHandlerInvoker.call(this, 'abort'));
this.xhr.addEventListener('error', getHandlerInvoker.call(this, 'error'));
this.xhr.open('GET', url);
this.xhr.responseType = 'blob';
};
Loader.prototype.addEventListener = function(evt, callback){
this.eventListeners[evt].push(callback);
};
Loader.prototype.removeEventListener = function(evt, callback){
var idx = this.eventListeners[evt].indexOf(callback);
if(idx !== -1){
this.eventListeners[evt].splice(idx, 1);
}
};
Loader.prototype.load = function(){
getHandlerInvoker.call(this, 'beforesend')({
name: 'beforesend',
target: this.xhr
});
this.xhr.send(null);
};
exports.WebFontLoader = Loader;
})(window);