Skip to content

Instantly share code, notes, and snippets.

@pamelafox
Created June 15, 2011 23:21
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 pamelafox/1028372 to your computer and use it in GitHub Desktop.
Save pamelafox/1028372 to your computer and use it in GitHub Desktop.
jsonp + lscache
//Lightweight JSONP fetcher - www.nonobtrusive.com
var JSONP = (function(){
var counter = 0, head, query, key, window = this;
function load(url) {
var script = document.createElement('script'),
done = false;
script.src = url;
script.async = true;
script.onload = script.onreadystatechange = function() {
if ( !done && (!this.readyState || this.readyState === "loaded" || this.readyState === "complete") ) {
done = true;
script.onload = script.onreadystatechange = null;
if ( script && script.parentNode ) {
script.parentNode.removeChild( script );
}
}
};
if ( !head ) {
head = document.getElementsByTagName('head')[0];
}
head.appendChild( script );
}
function jsonp(url, params, callbackParam, callbackFunc) {
query = "?";
params = params || {};
for ( key in params ) {
if ( params.hasOwnProperty(key) ) {
query += key + "=" + params[key] + "&";
}
}
// Check if its in localStorage first, immediately callback if so
var lskey = url + query;
var data = lscache.get(lskey);
if (data) {
callbackFunc(data);
} else {
var jsonp = "json" + (++counter);
window[ jsonp ] = function(data){
callbackFunc(data);
// Store there for 30 minutes
lscache.set(lskey, data, 60*30);
window[ jsonp ] = null;
try {
delete window[ jsonp ];
} catch (e) {}
};
var callbackParam = callbackParam || 'callback';
load(url + query + callbackParam + "=" + jsonp);
}
return jsonp;
}
return {
get:jsonp
};
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment