-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
39 lines (31 loc) · 898 Bytes
/
index.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
/* eslint-disable no-var */
'use strict'
var callbacks = {}
var bagName = '__jsonpCallbacks'
Object.defineProperty(window, bagName, { value: callbacks })
var jsonpIndex = 0
function jsonp (url, opts) {
var callbackName = 'jsonp' + jsonpIndex
var param = (opts && opts.param) || 'callback'
var sigil = url.indexOf('?') !== -1 ? '&' : '?'
var s = document.createElement('script')
s.async = true
s.src = url + sigil + param + '=' + encodeURIComponent(bagName + '.' + callbackName)
document.head.appendChild(s)
function cleanup () {
delete callbacks[callbackName]
document.head.removeChild(s)
}
return new Promise(function (resolve, reject) {
callbacks[callbackName] = resolve
s.onerror = reject
jsonpIndex += 1
}).then(function (result) {
cleanup()
return result
}, function (err) {
cleanup()
throw err
})
}
module.exports = jsonp