Created
May 29, 2017 03:55
-
-
Save esironal/0bab0f71af7e976237be8fa7ee4dd9e7 to your computer and use it in GitHub Desktop.
Lightweight example Jsonp Loader
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* jsonp.js, (c) Przemek Sobstel 2012, License: MIT */ | |
var $jsonp = (function(){ | |
var that = {}; | |
that.send = function(src, options) { | |
var options = options || {}, | |
callback_name = options.callbackName || 'callback', | |
on_success = options.onSuccess || function(){}, | |
on_timeout = options.onTimeout || function(){}, | |
timeout = options.timeout || 10; | |
var timeout_trigger = window.setTimeout(function(){ | |
window[callback_name] = function(){}; | |
on_timeout(); | |
}, timeout * 1000); | |
window[callback_name] = function(data){ | |
window.clearTimeout(timeout_trigger); | |
on_success(data); | |
}; | |
var script = document.createElement('script'); | |
script.type = 'text/javascript'; | |
script.async = true; | |
script.src = src; | |
document.getElementsByTagName('head')[0].appendChild(script); | |
}; | |
return that; | |
})(); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$jsonp.send('some_url?callback=handleStuff', { | |
callbackName: 'handleStuff', | |
onSuccess: function(json){ | |
console.log('success!', json); | |
}, | |
onTimeout: function(){ | |
console.log('timeout!'); | |
}, | |
timeout: 5 | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment