tinyJSONP.js

A very tiny vanilla JSONP library

Only 273 bytes !

I wonder how,

JSONP(uri, callback)

I wonder why,

  1. Because JavaScript lacks native JSONP implementation
  2. Github searches revealed libraries that did not meet my needs
  3. I don't want to load jQuery each time I need JSONP...
    And neither do you!

Yesterday you told me 'bout the blue blue sky,

Leave your suggestions in the comments!

And all that I can see... is another repository

Source code is below, for you to plop in your code

Minified Source Example

But first... enjoy this little animation


tinyJSONP.min.js minified by Closure Compiler

 var JSONP=function(e,c){var f=0;return function(a,g){a=-1===a.indexOf("?")?a+"?":a+"&";var d="_jsonp"+f++,b=c.createElement("script");b.src=a+"callback="+d;e[d]=function(a){g.call(e,a);c.body.removeChild(b);b=null;delete window[d]};c.body.appendChild(b)}}(window,document);

tinyJSONP.js

var JSONP = (function(win, doc) {
  // Initialize the counter
  var counter = 0;

  // Create the global JSONP function
  return function (url, callback) {
    // Prepare for callback parameter
    if (url.indexOf('?') === -1) {
      url += '?';
    } else {
      url += '&';
    }

    // Create the script
    var name = '_jsonp' + counter++;
    var script = doc.createElement('script');
    script.src = url + 'callback=' + name;

    // Create a temporary global callback
    win[name] = function(data) {
      // Call the callback
      callback.call(win, data);
      // Cleanup
      doc.body.removeChild(script);
      script = null;
      delete window[name];
    }

    // Load the JSONP
    doc.body.appendChild(script);
  }
})(window, document);

example.js

Get all Wikipedia results for The King of Pop

// Build the URI
var uri = 'https://en.wikipedia.org/w/api.php';
var query = '?action=opensearch&format=json';
query += '&search=michael+jackson';
uri += query;

// Get JSON data
JSONP(uri, function(data) {
  console.log(data[2][0]);
});

Yields: "Michael Joseph Jackson (August 29, 1958 – June 25, 2009) was an American singer, songwriter, and dancer."