Skip to content

Instantly share code, notes, and snippets.

@WebReflection
Last active June 12, 2026 09:30
Show Gist options
  • Select an option

  • Save WebReflection/b4199ea6c0dbd3dcb415444cb5e25122 to your computer and use it in GitHub Desktop.

Select an option

Save WebReflection/b4199ea6c0dbd3dcb415444cb5e25122 to your computer and use it in GitHub Desktop.
The easiest way to fetch JSON data when CORS is not an option but JSONP is
let p = 0;
const fetchp = (url, ..._) => new Promise((resolve, reject) => {
const src = new URL(url);
const callback = `__json${p++}`.replace('-', '_');
src.searchParams.set('callback', callback);
document.head.appendChild(Object.assign(
document.createElement('script'),
{ async: true, onerror: reject, src }
));
globalThis[callback] = value => {
delete globalThis[callback];
resolve(value);
};
});
@WebReflection

Copy link
Copy Markdown
Author

Example:

fetchp('https://example.com/unique-identifier/data.json').then(
  json => {
    console.log('That is it', json);
  }
)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment