Last active
August 29, 2015 14:21
-
-
Save calvinfroedge/e6207d115ac2d228972e to your computer and use it in GitHub Desktop.
Load and cache JSONP content
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
/** | |
* Load and cache JSONP data | |
*/ | |
var loadJSONP = function ( url, callback ) { | |
var setLocalData = false; | |
/* | |
* Setting a variable callback method since we're writing to window | |
*/ | |
var callbackMethod = url.replace(/[^a-z0-9]/g, '_') | |
/* | |
* Send data to the callback function, caching data if needed | |
*/ | |
window[callbackMethod] = function(data){ | |
if(setLocalData){ | |
//Cache for 1 day | |
var d = new Date(); | |
d.setDate(d.getDate()+1); | |
localStorage.setItem(url, JSON.stringify({expiry: d.getTime(), value: data})); | |
} | |
window[callback](data); | |
} | |
/* | |
* Make the JSONP request | |
*/ | |
function requestDataFromRemote(){ | |
// Create script with url and callback (if specified) | |
var ref = window.document.getElementsByTagName( 'script' )[ 0 ]; | |
var script = window.document.createElement( 'script' ); | |
script.src = url + (url.indexOf( '?' ) + 1 ? '&' : '?') + 'callback='+callbackMethod | |
// Insert script tag into the DOM (append to <head>) | |
ref.parentNode.insertBefore( script, ref ); | |
// After the script is loaded (and executed), remove it | |
script.onload = function () { | |
this.remove(); | |
}; | |
} | |
var stored = localStorage.getItem(url); | |
if(stored){ | |
console.log('stored'); | |
var now = (new Date()).getTime(); | |
var json = JSON.parse(stored); | |
console.log('expiry', json.expiry, 'now', now); | |
if(json.expiry > now){ | |
console.log('this one'); | |
window[callbackMethod](json.value); | |
} else { | |
console.log('that one'); | |
localStorage.removeItem(url); | |
setLocalData = true; | |
requestDataFromRemote(); | |
} | |
} else { | |
setLocalData = true; | |
requestDataFromRemote(); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment