Skip to content

Commit f1a1080

Browse files
committed
Add XHR2 fallback if fetch API is not available.
This adds support to parse meta data for images loaded via URL for Internet Explorer 10+.
1 parent 9326d2a commit f1a1080

File tree

2 files changed

+37
-3
lines changed

2 files changed

+37
-3
lines changed

js/load-image-fetch.js

Lines changed: 33 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@
2828
if (typeof fetch !== 'undefined' && typeof Request !== 'undefined') {
2929
loadImage.fetchBlob = function(url, callback, options) {
3030
if (loadImage.hasMetaOption(options)) {
31-
return fetch(new Request(url, options))
31+
fetch(new Request(url, options))
3232
.then(function(response) {
3333
return response.blob()
3434
})
@@ -37,8 +37,39 @@
3737
console.log(err) // eslint-disable-line no-console
3838
callback()
3939
})
40+
} else {
41+
callback()
42+
}
43+
}
44+
} else if (
45+
// Check for XHR2 support:
46+
typeof XMLHttpRequest !== 'undefined' &&
47+
typeof ProgressEvent !== 'undefined'
48+
) {
49+
loadImage.fetchBlob = function(url, callback, options) {
50+
if (loadImage.hasMetaOption(options)) {
51+
// eslint-disable-next-line no-param-reassign
52+
options = options || {}
53+
var req = new XMLHttpRequest()
54+
req.open(options.method || 'GET', url)
55+
if (options.headers) {
56+
Object.keys(options.headers).forEach(function(key) {
57+
req.setRequestHeader(key, options.headers[key])
58+
})
59+
}
60+
req.withCredentials = options.credentials === 'include'
61+
req.responseType = 'blob'
62+
req.onload = function() {
63+
callback(req.response)
64+
}
65+
req.onerror = req.onabort = req.ontimeout = function(e) {
66+
console.log(e) // eslint-disable-line no-console
67+
callback()
68+
}
69+
req.send(options.body)
70+
} else {
71+
callback()
4072
}
41-
callback()
4273
}
4374
}
4475
})

test/test.js

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -875,7 +875,10 @@
875875
})
876876
})
877877

878-
if ('fetch' in window && 'Request' in window) {
878+
if (
879+
('fetch' in window && 'Request' in window) ||
880+
('XMLHttpRequest' in window && 'ProgressEvent' in window)
881+
) {
879882
describe('Fetch', function() {
880883
it('Should fetch image URL as blob if meta option is true', function(done) {
881884
expect(

0 commit comments

Comments
 (0)