Skip to content

Instantly share code, notes, and snippets.

@WebReflection
Created August 8, 2025 09:59
Show Gist options
  • Save WebReflection/b4199ea6c0dbd3dcb415444cb5e25122 to your computer and use it in GitHub Desktop.
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, ..._) => {
const { promise, resolve, reject } = Promise.withResolvers();
const src = new URL(url);
const callback = `__json${p++}`;
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);
};
return promise;
};
@WebReflection
Copy link
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