Created
June 15, 2011 23:21
-
-
Save pamelafox/1028372 to your computer and use it in GitHub Desktop.
jsonp + lscache
This file contains 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
//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