Skip to content

Instantly share code, notes, and snippets.

@zakariamouhid
Last active November 12, 2020 22:56
Show Gist options
  • Save zakariamouhid/a2aacd0984506d27de1e9700ce1f70dd to your computer and use it in GitHub Desktop.
Save zakariamouhid/a2aacd0984506d27de1e9700ce1f70dd to your computer and use it in GitHub Desktop.
simple jsonp that supports browser caching
const fetchJSONP = ((callback, callbackName) => {
const map = new WeakMap();
window[callbackName] = json => {
const script = document.currentScript;
const fn = map.get(script);
if (fn) {
map.delete(script);
fn(json);
script.remove();
}
};
return url => new Promise(resolve => {
const script = document.createElement('script');
url += url.indexOf('?') !== -1 ? '&' : '?';
url += callback + '=' + callbackName;
map.set(script, resolve);
script.src = url;
document.body.append(script);
});
})('callback', '_jsonp_global_');
fetch = ((nativeFetch) => {
return (url, options) => {
if (options && options.method.toUpperCase() === 'JSONP') {
return fetchJSONP(url)
.then(json => new Response(JSON.stringify(json)));
}
return nativeFetch(url, options);
};
})(fetch);
// test on jsfiddle
// https://jsfiddle.net/zakariamouhid/pyzagmx7/2/
// it depends on document.currentscript
// https://caniuse.com/document-currentscript
// Examples
const url = 'https://zakariamouhid.blogspot.com/feeds/posts/default?alt=json-in-script&max-results=0';
fetchJSONP(url).then(json => {
console.log(json.version);
});
fetch(url, { method: 'JSONP' })
.then(res => res.json())
.then(json => {
console.log(json.version);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment