Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Simple JSONP in vanilla JS
function(data) {
var loadJSONP = (function(){
var unique = 0;
return function(url, callback, context) {
var name = "_jsonp_" + unique++;
if (url.match(/\?/)) url += "&callback="+name;
else url += "?callback="+name;
// Create script
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = url;
// Setup handler
window[name] = function(data){ || window), data);
script = null;
delete window[name];
// Load JSON
Copy link

DrStrangeLove commented Sep 27, 2011

Great gist!!
But what if some server script accepts different parameter instead of callback??
it could be http://xxx.yyy/script?jsonp=callbackname

Copy link

gf3 commented Sep 27, 2011

@DrStrangeLove It wouldn't be difficult to add a third argument, such as an options object. It could be used to control the name of the callback parameter.

Copy link

ManasJayanth commented Nov 14, 2014

@gf3 In line 28 I faced issues when name started with a double underscore. I had to use jsonp_ as the prefix (non underscore prefix)

Copy link

jimmywarting commented May 1, 2017

I modified it a bit to act little bit more like the new fetch api and using promises

 const fetchJSONP = (unique => url => 
   new Promise(rs => {
     // INIT
     let script = document.createElement('script')
     let name = "_jsonp_" + unique++
     if (url.match(/\?/)) url += "&callback="+name
     else url += "?callback="+name
     script.src = url
     window[name] = json => {
       rs(new Response(JSON.stringify(json)))
       delete window[name]

Copy link

michaelpumo commented May 11, 2017


More es2015 friendly and ESLinted according to AirBnb:

const fetchJSONP = (unique => url =>
  new Promise(rs => {
    const script = document.createElement('script');
    const name = `_jsonp_${unique++}`;

    if (url.match(/\?/)) {
      url += `&callback=${name}`;
    } else {
      url += `?callback=${name}`;

    script.src = url;
    window[name] = json => {
      rs(new Response(JSON.stringify(json)));
      delete window[name];



Copy link

ghost commented Mar 5, 2018

can someone explain how it's works? because i have no idea.

Copy link

janbalaz commented Jul 24, 2018

Thanks for the code, it's good, but I wouldn't recommend using simple incrementation of counter to achieve unique callback name. I suggest using timestamp or random number. Although this code cleans up afterwards, when I used it twice in 2 widgets on the same site, there were collisions.
I used this solution:

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