Skip to content

Instantly share code, notes, and snippets.

@sindresorhus
Created February 24, 2012 12:38
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save sindresorhus/1900694 to your computer and use it in GitHub Desktop.
Save sindresorhus/1900694 to your computer and use it in GitHub Desktop.
JSONP function - Easily fetch remote JSONP files
// Example usage: Fetch it's own code from GitHub
JSONP( 'https://api.github.com/gists/1900694?callback=?', function( response ) {
console.log( 'JSONP function:', response.data.files['jsonp.js'].content );
});
function JSONP( url, callback ) {
var id = ( 'jsonp' + Math.random() * new Date() ).replace('.', '');
var script = document.createElement('script');
script.src = url.replace( 'callback=?', 'callback=' + id );
document.body.appendChild( script );
window[ id ] = function( data ) {
if (callback) {
callback( data );
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment