Last active
November 12, 2020 22:56
-
-
Save zakariamouhid/a2aacd0984506d27de1e9700ce1f70dd to your computer and use it in GitHub Desktop.
simple jsonp that supports browser caching
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
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_'); |
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
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); |
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
// 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