Skip to content

Instantly share code, notes, and snippets.

@clhenrick
Forked from gf3/jsonp.js
Last active August 29, 2015 14:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save clhenrick/fcefcc4dee56f7df653a to your computer and use it in GitHub Desktop.
Save clhenrick/fcefcc4dee56f7df653a to your computer and use it in GitHub Desktop.
/**
* loadJSONP( url, hollaback [, context] ) -> Null
* - url (String): URL to data resource.
* - hollaback (Function): Function to call when data is successfully loaded,
* it receives one argument: the data.
* - context (Object): Context to invoke the hollaback function in.
*
* Load external data through a JSONP interface.
*
* ### Examples
*
* loadJSONP(
* 'http://www.gigpark.com/businesses/runlevel6.json',
* function(data) {
* console.log(data)
* }
* )
**/
var loadJSONP = (function loadJSONP_outer( window, document, undefined ) { var uuid, head, main_script
uuid = 0
head = document.head || document.getElementsByTagName( 'head' )[0]
main_script = document.createElement( 'script' )
main_script.type = 'text/javascript'
return function loadJSONP_inner( url, callback, context ) { var name, script
// INIT
name = '__jsonp_' + uuid++
if ( url.match(/\?/) )
url += '&callback=' + name
else
url += '?callback=' + name
// Create script
script = main_script.cloneNode()
script.src = url
// Setup handler
window[name] = function( data ) {
callback.call( ( context || window ), data )
head.removeChild( script )
script = null
delete window[name]
}
// Load JSON
head.appendChild( script )
}
})( window, document )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment