Design & Download
Your JS Library
in Seconds!!!

Snippet: jsonp()

Written by Christopher West (cwest) on November 14, 2015.
function jsonp(url, callback, opt_callbackParamName) {
  var parent = document.getElementsByTagName('head')[0] || document.body;
  var script = document.createElement('script');
  var callbackName = '__jsonp';
  do {
    callbackName = (callbackName + Math.random()).replace('.', '');
  } while (has(__global, callbackName));
  var called;
  __global[callbackName] = function() {
    if (!called) {
      called = 1;
      delete __global[callbackName];
      callback.apply(this, arguments);
    }
  };
  script.src = (url + '&'
    + encodeURIComponent(opt_callbackParamName || 'callback')
    + '=' + callbackName).replace(/(^[^\?&]*)&/, '$1?');
  script.type = 'text/JavaScript';
  parent.appendChild(script);
}