Skip to content

Commit c889c49

Browse files
author
a-jie
committed
update v1.1.0
update v1.1.0
1 parent 77b2b77 commit c889c49

File tree

6 files changed

+97
-62
lines changed

6 files changed

+97
-62
lines changed

.gitignore

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
2+
node_modules/
3+
package-lock.json

LICENSE

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
MIT License
2+
3+
Copyright (c) 2018 fetch-extras
4+
5+
Permission is hereby granted, free of charge, to any person obtaining a copy
6+
of this software and associated documentation files (the "Software"), to deal
7+
in the Software without restriction, including without limitation the rights
8+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+
copies of the Software, and to permit persons to whom the Software is
10+
furnished to do so, subject to the following conditions:
11+
12+
The above copyright notice and this permission notice shall be included in all
13+
copies or substantial portions of the Software.
14+
15+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21+
SOFTWARE.

dist/index.js

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

lib/index.js

Lines changed: 65 additions & 57 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,28 @@
11
;
22
(function () {
3-
'use strict';
3+
'use strict'
44

5-
const fetchBak = window.fetch
6-
let index = 0
5+
var isBrowser = new Function("try {return this===window}catch(e){ return false}");
6+
if (!isBrowser() || !window.fetch) return;
77

8-
window.fetch = function (reqOrUrl, options) {
9-
const method = getValFromOpt(options, 'method', '')
8+
fetchPolyfill();
109

11-
if (method.toLowerCase() == 'jsonp') {
12-
return jsonp(reqOrUrl, options)
13-
} else {
14-
return fetchBak.apply(window, arguments)
10+
////////////////////////////////////////////////////////////////////////////
11+
//
12+
// fetch polyfill func
13+
//
14+
////////////////////////////////////////////////////////////////////////////
15+
function fetchPolyfill() {
16+
var fetchBak = window.fetch;
17+
18+
window.fetch = function (reqOrUrl, options) {
19+
var method = getValFromOpt(options, 'method', '');
20+
21+
if (method.toLowerCase() == 'jsonp') {
22+
return jsonp(reqOrUrl, options);
23+
} else {
24+
return fetchBak.apply(window, arguments);
25+
}
1526
}
1627
}
1728

@@ -22,44 +33,45 @@
2233
////////////////////////////////////////////////////////////////////////////
2334
function jsonp(reqOrUrl, options) {
2435
if (!reqOrUrl) {
25-
printfError("1 argument required, but only 0 present")
26-
return null
36+
new Error("1 argument required, but only 0 present");
37+
return null;
2738
}
2839

29-
return new Promise((resolve, reject) => {
40+
return new Promise(function (resolve, reject) {
3041
// create cache data
31-
const id = generateId()
32-
const timeout = getValFromOpt(options, 'callback', 8000) << 0
33-
const callback = getValFromOpt(options, 'callback') || getValFromOpt(options, 'cb') || 'callback'
34-
const callbackName = getValFromOpt(options, 'callbackName', id)
35-
const tid = setTimeout(()=>{destroy(', it is timeout')}, timeout)
42+
var id = generateId();
43+
var timeout = getValFromOpt(options, 'callback', 8000) << 0;
44+
var callback = getValFromOpt(options, 'callback') || getValFromOpt(options, 'cb') || 'callback';
45+
var callbackName = getValFromOpt(options, 'callbackName', id);
46+
var tid = setTimeout(function () { destroy(', it is timeout'); }, timeout);
3647

3748
// generate url
38-
let url = typeof reqOrUrl === 'object' ? reqOrUrl.url : reqOrUrl + ''
39-
url += (url.indexOf('?') > 0 ? '&' : '?').replace('?&', '?')
40-
url += callback + '=' + callbackName
49+
var url = typeof reqOrUrl === 'object' ? reqOrUrl.url : reqOrUrl + '';
50+
url += (url.indexOf('?') > 0 ? '&' : '?').replace('?&', '?');
51+
url += callback + '=' + callbackName;
4152

4253
// create script tag
43-
const head = document.getElementsByTagName('head')[0] || document.head
44-
const script = document.createElement('script')
45-
script.src = url
46-
script.onerror = destroy
47-
head.appendChild(script)
48-
49-
window[callbackName] = (res) => {
50-
resolve(new Response(res, url))
51-
destroy()
54+
var head = document.getElementsByTagName('head')[0] || document.head;
55+
var script = document.createElement('script');
56+
script.src = url;
57+
script.onerror = destroy;
58+
head.appendChild(script);
59+
60+
window[callbackName] = function (res) {
61+
resolve(new Response(res, url));
62+
destroy();
5263
}
5364

5465
// destroy func
5566
function destroy(msg) {
5667
try {
57-
deleteFromWin(callbackName)
58-
script.parentNode.removeChild(script)
59-
clearTimeout(tid)
68+
deleteFromWin(callbackName);
69+
script.parentNode.removeChild(script);
70+
clearTimeout(tid);
6071
} catch (e) { }
6172

62-
reject(new Error(`JSONP request to ${url}${msg || ''}`))
73+
msg = msg || '';
74+
reject(new Error('JSONP request to ' + url + msg));
6375
}
6476
})
6577
}
@@ -70,28 +82,28 @@
7082
//
7183
////////////////////////////////////////////////////////////////////////////
7284
function Response(res, url) {
73-
this.ok = true
74-
this.status = 200
75-
this.type = 'default'
76-
this.url = url || ''
77-
this.statusText = 'OK'
78-
this.bodyUsed = false
79-
this._bodyText = res
85+
this.ok = true;
86+
this.status = 200;
87+
this.type = 'default';
88+
this.url = url || '';
89+
this.statusText = 'OK';
90+
this.bodyUsed = false;
91+
this._bodyText = res;
8092
}
8193

8294
Response.prototype = {
8395
text: function () {
84-
this.bodyUsed = true
85-
return Promise.resolve(this._bodyText)
96+
this.bodyUsed = true;
97+
return Promise.resolve(this._bodyText);
8698
},
8799

88100
json: function () {
89-
this.bodyUsed = true
90-
return Promise.resolve(toJson(this._bodyText))
101+
this.bodyUsed = true;
102+
return Promise.resolve(toJson(this._bodyText));
91103
},
92104

93105
clone: function () {
94-
return new Response(this._bodyText, url)
106+
return new Response(this._bodyText, url);
95107
}
96108
}
97109

@@ -100,8 +112,9 @@
100112
// generate Id
101113
//
102114
////////////////////////////////////////////////////////////////////////////
115+
var index = 0;
103116
function generateId() {
104-
return `jsonpcallback_${~~(Math.random() * Math.pow(10, 7))}_${++index}`
117+
return 'jsonpcallback_' + ~~(Math.random() * Math.pow(10, 7)) + '_' + (++index);
105118
}
106119

107120
////////////////////////////////////////////////////////////////////////////
@@ -111,7 +124,7 @@
111124
////////////////////////////////////////////////////////////////////////////
112125
function deleteFromWin(key) {
113126
try {
114-
delete window[key]
127+
delete window[key];
115128
} catch (e) { window[key] = undefined }
116129
}
117130

@@ -126,7 +139,6 @@
126139
return defaultVal;
127140
}
128141

129-
130142
////////////////////////////////////////////////////////////////////////////
131143
//
132144
// convert to json data
@@ -135,19 +147,15 @@
135147
function toJson(res) {
136148
if (typeof ref === 'string') {
137149
try {
138-
return JSON.parse(res)
150+
return JSON.parse(res);
139151
} catch (e) {
140-
return eval(`(${res})`)
152+
return eval('(' + res + ')');
141153
} finally {
142-
return res
154+
return res;
143155
}
144156
} else {
145-
return res
157+
return res;
146158
}
147159
}
148160

149-
function printfError() {
150-
window.console && console.error.apply(console, arguments)
151-
}
152-
153-
})();
161+
})()

package.json

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,23 @@
11
{
22
"name": "fetch-jsonp-polyfill",
3-
"version": "1.0.0",
3+
"version": "1.1.0",
44
"description": "a jsonp fetch polyfill",
5-
"main": "bin/index.js",
5+
"main": "dist/index.js",
66
"directories": {
77
"test": "test"
88
},
99
"scripts": {
10+
"build": "uglifyjs ./lib/index.js -o ./dist/index.js -c -m",
1011
"test": "jest"
1112
},
1213
"keywords": [
1314
"fetch",
1415
"jsonp"
1516
],
1617
"author": "a-jie",
17-
"license": "ISC",
18+
"license": "MIT",
1819
"devDependencies": {
19-
"jest": "^22.3.0"
20+
"jest": "^22.3.0",
21+
"uglify-js": "^3.3.17"
2022
}
2123
}

test/test.html

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
<script src="../libs/index.js"></script>
1+
<script src="../lib/index.js"></script>
22

33
<script>
44
var URL = 'http://jsfiddle.net/echo/jsonp/';

0 commit comments

Comments
 (0)