Skip to content

Instantly share code, notes, and snippets.

@GarrettWeinberg
Created December 16, 2020 18:46
Show Gist options
  • Save GarrettWeinberg/e0e438b688a65ded8ecc93d7dfc1c6d4 to your computer and use it in GitHub Desktop.
Save GarrettWeinberg/e0e438b688a65ded8ecc93d7dfc1c6d4 to your computer and use it in GitHub Desktop.
// Set JS for jsonp callback
let jsonpID = 0;
function jsonp(url, timeout = 7500) {
const head = document.querySelector('head');
// set unique identifier for function
jsonpID = Math.round(Math.random() * 1000000000);
return new Promise((resolve, reject) => {
let script = document.createElement('script');
const callbackName = `jsonpCallback${jsonpID}`;
script.src = encodeURI(`${url}&callback=${callbackName}`);
script.async = true;
const timeoutId = window.setTimeout(() => {
cleanUp();
return reject(new Error('Timeout'));
}, timeout);
window[callbackName] = data => {
cleanUp();
return resolve(data);
};
script.addEventListener('error', error => {
cleanUp();
return reject(error);
});
// Define cleanup function
function cleanUp() {
window[callbackName] = undefined;
head.removeChild(script);
window.clearTimeout(timeoutId);
script = null;
}
// append script inside <head>
head.appendChild(script);
});
}
jsonp(
FormatsApi
)
.then(console.log)
.catch(console.error);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment