Skip to content

Instantly share code, notes, and snippets.

@huruji
Created November 1, 2017 13:45
Show Gist options
  • Save huruji/cb53fec15ac3d4aa3b932b67518c1c64 to your computer and use it in GitHub Desktop.
Save huruji/cb53fec15ac3d4aa3b932b67518c1c64 to your computer and use it in GitHub Desktop.
(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