-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathxhrimage.js
More file actions
83 lines (60 loc) · 2.15 KB
/
xhrimage.js
File metadata and controls
83 lines (60 loc) · 2.15 KB
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
define(['marionette'], function() {
var XHRImage = Image
if (!('imagecache' in app)) app.imagecache = {}
XHRImage.prototype.load = function(url, callback) {
var self = this
this.completedPercentage = 0
var xhr = new XMLHttpRequest()
// dont fetch image string
if (url.startsWith('data:image')) {
self.src = url
if (callback) callback(this)
return
}
// retrieve from cache if possible
if (url in app.imagecache) {
self.src = app.imagecache[url]
if (callback) callback(this)
return
}
var req = url + (url.indexOf('?') > -1 ? '&prop=': '?prop=') + app.prop
xhr.open('GET', req, true)
if (app.token) xhr.setRequestHeader('Authorization','Bearer ' + app.token);
xhr.responseType = 'arraybuffer'
xhr.onload = function(e) {
if (xhr.status == 0 || xhr.status != 200) {
self.onerror(xhr.status, e)
return
}
var h = xhr.getAllResponseHeaders()
var m = h.match(/^Content-Type:\s*(.*?)$/mi)
var mimeType = m[1] || 'image/png';
var blob = new Blob([this.response], { type: mimeType })
self.src = window.URL.createObjectURL(blob)
app.imagecache[url] = self.src
if (callback) callback(self)
}
xhr.onprogress = function(e) {
if (e.lengthComputable) {
var pc = parseInt( ( e.loaded / e.total ) * 100 )
if (pc != self.completedPercentage) {
self.completedPercentage = pc
if (self.onprogress) self.onprogress(pc)
}
self.completedPercentage = pc
}
}
xhr.onloadstart = function() {
self.completedPercentage = 0
}
xhr.onloadend = function() {
self.completedPercentage = 100
}
xhr.onerror = function () {
console.log('img network error')
// self.onerror(arguments)
}
xhr.send()
}
return XHRImage
})