1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 | ;(function (factory) {
|
15 | 'use strict'
|
16 | if (typeof define === 'function' && define.amd) {
|
17 |
|
18 | define(['./load-image'], factory)
|
19 | } else if (typeof module === 'object' && module.exports) {
|
20 | factory(require('./load-image'))
|
21 | } else {
|
22 |
|
23 | factory(window.loadImage)
|
24 | }
|
25 | })(function (loadImage) {
|
26 | 'use strict'
|
27 |
|
28 | var global = loadImage.global
|
29 |
|
30 | if (
|
31 | global.fetch &&
|
32 | global.Request &&
|
33 | global.Response &&
|
34 | global.Response.prototype.blob
|
35 | ) {
|
36 | loadImage.fetchBlob = function (url, callback, options) {
|
37 | |
38 |
|
39 |
|
40 |
|
41 |
|
42 |
|
43 | function responseHandler(response) {
|
44 | return response.blob()
|
45 | }
|
46 | if (global.Promise && typeof callback !== 'function') {
|
47 | return fetch(new Request(url, callback)).then(responseHandler)
|
48 | }
|
49 | fetch(new Request(url, options))
|
50 | .then(responseHandler)
|
51 | .then(callback)
|
52 | [
|
53 |
|
54 |
|
55 | 'catch'
|
56 | ](function (err) {
|
57 | callback(null, err)
|
58 | })
|
59 | }
|
60 | } else if (
|
61 | global.XMLHttpRequest &&
|
62 |
|
63 | new XMLHttpRequest().responseType === ''
|
64 | ) {
|
65 | loadImage.fetchBlob = function (url, callback, options) {
|
66 | |
67 |
|
68 |
|
69 |
|
70 |
|
71 |
|
72 | function executor(resolve, reject) {
|
73 | options = options || {}
|
74 | var req = new XMLHttpRequest()
|
75 | req.open(options.method || 'GET', url)
|
76 | if (options.headers) {
|
77 | Object.keys(options.headers).forEach(function (key) {
|
78 | req.setRequestHeader(key, options.headers[key])
|
79 | })
|
80 | }
|
81 | req.withCredentials = options.credentials === 'include'
|
82 | req.responseType = 'blob'
|
83 | req.onload = function () {
|
84 | resolve(req.response)
|
85 | }
|
86 | req.onerror = req.onabort = req.ontimeout = function (err) {
|
87 | if (resolve === reject) {
|
88 |
|
89 | reject(null, err)
|
90 | } else {
|
91 | reject(err)
|
92 | }
|
93 | }
|
94 | req.send(options.body)
|
95 | }
|
96 | if (global.Promise && typeof callback !== 'function') {
|
97 | options = callback
|
98 | return new Promise(executor)
|
99 | }
|
100 | return executor(callback, callback)
|
101 | }
|
102 | }
|
103 | })
|