Created
November 1, 2017 13:45
-
-
Save huruji/cb53fec15ac3d4aa3b932b67518c1c64 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function(global){ | |
function generateJsonpCallback() { | |
return `jsonpcallback_${Date.now()}_${Math.floor(Math.random() * 100000)}`; | |
} | |
function removeScript(id) { | |
document.body.removeChild(document.getElementById(id)); | |
} | |
function removeFunc(name) { | |
delete global[name]; | |
} | |
function jsonp(url, options = {timeout:3000}) { | |
const timeout = options.timeout; | |
let timeId; | |
return new Promise((resolve, reject) => { | |
const funcName = generateJsonpCallback(); | |
global[funcName] = (res) => { | |
resolve(res); | |
timeId = setTimeout(() => { | |
removeScript(funcName); | |
removeFunc(funcName); | |
}, timeout) | |
}; | |
const script = document.createElement('script'); | |
script.src = `${url}?callback=${funcName}`; | |
script.id = funcName; | |
script.type = 'text/javascript'; | |
document.body.appendChild(script); | |
script.onerror = () => { | |
reject(new Error(`fetch ${url} failed`)); | |
removeScript(funcName); | |
removeFunc(funcName); | |
if(timeId) clearTimeout(timeId); | |
} | |
}) | |
} | |
window.jsonp = jsonp; | |
})(window); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment